Wagner Fischer algorithm implementation in java -
i trying implement wagner-fischer algorithm
in java using wikipedia reference
java code:
public class stringdistance { public static void main(string[] args) { int i, j, m, n, temp, tracker; int[][] d = new int[50][50]; string s = "kitten"; string t = "sitting"; char u[] = s.tochararray(); char v[] = t.tochararray(); m = u.length; n = v.length; (i = 0; <= m; i++) { d[i][0] = i; } (j = 0; j <= n; j++) { d[0][j] = j; } (j = 1; j <= m; j++) { (i = 1; <= n; i++) { if (u[i - 1] == v[j - 1]) { tracker = 0; } else { tracker = 1; } temp = math.min((d[i - 1][j] + 1), (d[i][j - 1] + 1)); d[i][j] = math.min(temp, (d[i - 1][j - 1] + tracker)); } } system.out.println("the levenstien distance" + d[n][m]); } }
but above code working strings equal lengths. if want make work unequal strings.please let me know how overcome issue.
i getting index out of bounds error :
exception in thread "main" java.lang.arrayindexoutofboundsexception: 6 @ stringdistance.main(stringdistance.java:32)
let's rid of of local variables make clearer why happening:
for (j = 1; j <= u.length; j++) { (i = 1; <= v.length; i++) { if (u[i - 1] == v[j - 1]) { tracker = 0; } else { tracker = 1; }
you're using i - 1
(which guaranteed in range v
) index u
, j - 1
(which guaranteed in range u
) index v
.
so suspect expression:
u[i - 1] == v[j - 1]
should be
u[j - 1] == v[i - 1]
i'd suggest declaring variables @ point of first use, in minimal scope, , using 0-based indexing rather 1-based. , conditional operator helps too. loop become:
for (int j = 0; j < u.length; j++) { (int = 0; < v.length; i++) { int tracker = u[j] == v[i] ? 0 : 1; int temp = math.min(d[i][j + 1] + 1, d[i + 1][j] + 1); d[i + 1][j + 1] = math.min(temp, d[i][j] + tracker); } }
Comments
Post a Comment