C Program to Implement Levenshtein Distance Computing Algorithm

This is a C Program to implement online search. The Wagner–Fischer algorithm is a dynamic programming algorithm that measures the Levenshtein distance between two strings of characters.
For example, the Levenshtein distance between “kitten” and “sitting” is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits:

Here is source code of the C Program to Implement Levenshtein Distance Computing Algorithm. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <stdio.h>
  2. #include <math.h>
  3. int d[100][100];
  4. #define MIN(x,y) ((x) < (y) ? (x) : (y))
  5. main() {
  6.     int i, j, m, n, temp, tracker;
  7.     char s[] = "kitten";
  8.     char t[] = "sitting";
  9.     m = strlen(s);
  10.     n = strlen(t);
  11.  
  12.     for (i = 0; i <= m; i++)
  13.         d[0][i] = i;
  14.     for (j = 0; j <= n; j++)
  15.         d[j][0] = j;
  16.  
  17.     for (j = 1; j <= m; j++) {
  18.         for (i = 1; i <= n; i++) {
  19.             if (s[i - 1] == t[j - 1]) {
  20.                 tracker = 0;
  21.             } else {
  22.                 tracker = 1;
  23.             }
  24.             temp = MIN((d[i-1][j]+1),(d[i][j-1]+1));
  25.             d[i][j] = MIN(temp,(d[i-1][j-1]+tracker));
  26.         }
  27.     }
  28.     printf("the Levinstein distance is %d\n", d[n][m]);
  29.  
  30. }

Output:

$ gcc LevenshteinDistance.c
$ ./a.out
 
The Levinstein distance is 3

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.