ISourceCode

Make the frequent cases fast and the rare case correct

Wagner–Fischer algorithm – To find Levenshtein distance ( C program )

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:

kitten → sitten (substitution of ‘s’ for ‘k’)
sitten → sittin (substitution of ‘i’ for ‘e’)
sittin → sitting (insertion of ‘g’ at the end).

Computing the Levenshtein distance is based on the observation that if we reserve a matrix to hold the Levenshtein distances between all prefixes of the first string and all prefixes of the second, then we can compute the values in the matrix by flood filling the matrix, and thus find the distance between the two full strings as the last value computed.

                k 	i 	t 	t 	e 	n
	0 	1 	2 	3 	4 	5 	6
s 	1 	1 	2 	3 	4 	5 	6
i 	2 	2 	1 	2 	3 	4 	5
t 	3 	3 	2 	1 	2 	3 	4
t 	4 	4 	3 	2 	1 	2 	3
i 	5 	5 	4 	3 	2 	2 	3
n 	6 	6 	5 	4 	3 	3 	2
g 	7 	7 	6 	5 	4 	4 	3

CODE:

/* http://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm */
#include <stdio.h>
#include <math.h>
int d[100][100];
#define MIN(x,y) ((x) < (y) ? (x) : (y))
main()
{
	int i,j,m,n,temp,tracker;
	char s[] = "kitten";
	char t[] = "sitting";
	m = strlen(s);
	n = strlen(t);

	for(i=0;i<=m;i++)
		d[0][i] = i;
	for(j=0;j<=n;j++)
		d[j][0] = j;

	for (j=1;j<=m;j++)
	{
		for(i=1;i<=n;i++)
		{
			if(s[i-1] == t[j-1])
			{
				tracker = 0;
			}
			else{
				tracker = 1;
			}
			temp = MIN((d[i-1][j]+1),(d[i][j-1]+1));
			d[i][j] = MIN(temp,(d[i-1][j-1]+tracker));
		}
	}
	printf("the Levinstein distance is %d\n",d[n][m]);

}

OUTPUT:
$ ./a.exe
the Levinstein distance is 3

References: Wikipedia entry for Levenshtein distance.

Thanks for reading !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: