Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REVIEW PURPOSE] Add LEVENSHTEIN Java function implementation #26

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1717,4 +1717,37 @@ public void eval() {
out.end = outBytea.length;
}
}

/**
* Calculates the levenshtein distance of given strings.
*/
@FunctionTemplate(name = "levenshtein", scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL)
public static class Levenshtein implements SimpleFunction {
@Param VarCharHolder in1;
@Param VarCharHolder in2;
@Output IntHolder out;

@Override
public void setup() {}

@Override
public void eval() {
int len1 = in1.end - in1.start;
int len2 = in2.end - in2.start;
// dist[i][j] represents the Levenstein distance between the strings
int[][] dist = new int[len1 + 1][len2 + 1];
for (int i = 0; i <= len1; i++) dist[i][0] = i;
for (int j = 1; j <= len2; j++) dist[0][j] = j;
for (int j = 0; j < len2; j++) {
for (int i = 0; i < len1; i++) {
if(in1.buffer.getByte(i) == in2.buffer.getByte(j)) {
dist[i + 1][j + 1] = dist[i][j];
} else {
dist[i + 1][j + 1] = Math.min(Math.min(dist[i][j + 1] + 1, dist[i + 1][j] + 1), dist[i][j] + 1);
}
}
}
out.value = dist[len1][len2];
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -343,4 +343,15 @@ public void stringfuncs(){
});
}

@Test
public void levenshtein(){
testFunctions(new Object[][]{
{ "levenshtein('test', 'task')", 2},
{ "levenshtein('kitten', 'sitting')", 3},
{ "levenshtein('', 'a')", 1},
{ "levenshtein('cat', 'coat')", 1},
{ "levenshtein('book', 'back')", 2}
});
}

}