Skip to content

Commit bf07501

Browse files
author
Barbu Paul - Gheorghe
committed
added the levenshtein distance algorithm
1 parent 543c31a commit bf07501

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

l.in

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ioana dania

levenshtein_distance.c

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Calculate the levenshtein distance between two strings
3+
*/
4+
#include <stdio.h>
5+
#include <string.h>
6+
7+
int d[100][100]; //change this if one of the strings is longer than 100 chars
8+
9+
int minimum_of_three(int x, int y, int z){
10+
if(x<y){
11+
y = x;
12+
}
13+
14+
if(y<z){
15+
z = y;
16+
}
17+
18+
return z;
19+
}
20+
21+
int levenshtein_distance(char* a, char* b){
22+
int length_a = strlen(a), length_b = strlen(b);
23+
24+
for(int i=0; i<length_a; i++){
25+
d[i][0] = i;
26+
}
27+
28+
for(int i=0; i<length_b; i++){
29+
d[0][i] = i;
30+
}
31+
32+
for(int i=1; i<length_a; i++){
33+
for(int j=1; j<length_b; j++){
34+
if(a[i] == b[j]){
35+
d[i][j] = d[i-1][j-1];
36+
}
37+
else{
38+
d[i][j] = 1 + minimum_of_three(d[i-1][j], d[i][j-1], d[i-1][j-1]);
39+
}
40+
}
41+
}
42+
43+
return d[length_a-1][length_b-1];
44+
}
45+
46+
int main(){
47+
char a[100], b[100], pa[100] = " ", pb[100] = " ";
48+
FILE *f;
49+
50+
f = fopen("l.in", "r");
51+
52+
fscanf(f, "%s %s", a, b);
53+
54+
//need this in order to have the same starting point in both strings
55+
strcat(pa, a);
56+
strcat(pb, b);
57+
58+
printf("%d\n",levenshtein_distance(pa, pb));
59+
60+
fclose(f);
61+
}

0 commit comments

Comments
 (0)