Skip to content

Instantly share code, notes, and snippets.

@rogierslag
Last active December 23, 2021 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogierslag/3418c4948c794fa79c30706adb90a672 to your computer and use it in GitHub Desktop.
Save rogierslag/3418c4948c794fa79c30706adb90a672 to your computer and use it in GitHub Desktop.
Levenshtein Java
import java.util.Arrays;
// Taken from https://www.baeldung.com/java-levenshtein-distance#dynamic-programming-approach
class Levenshtein {
private static int costOfSubstitution(char a, char b) {
return a == b ? 0 : 1;
}
private static int min(int... numbers) {
return Arrays.stream(numbers)
.min().orElse(Integer.MAX_VALUE);
}
public static int calculateNaive(String x, String y) {
if (x.isEmpty()) {
return y.length();
}
if (y.isEmpty()) {
return x.length();
}
int substitution = calculateNaive(x.substring(1), y.substring(1))
+ costOfSubstitution(x.charAt(0), y.charAt(0));
int insertion = calculateNaive(x, y.substring(1)) + 1;
int deletion = calculateNaive(x.substring(1), y) + 1;
return min(substitution, insertion, deletion);
}
static int calculateDP(String x, String y) {
int[][] dp = new int[x.length() + 1][y.length() + 1];
for (int i = 0; i <= x.length(); i++) {
for (int j = 0; j <= y.length(); j++) {
if (i == 0) {
dp[i][j] = j;
}
else if (j == 0) {
dp[i][j] = i;
}
else {
dp[i][j] = min(dp[i - 1][j - 1]
+ costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)),
dp[i - 1][j] + 1,
dp[i][j - 1] + 1);
}
}
}
return dp[x.length()][y.length()];
}
private static String measureCalculation(String s1, String s2) {
long start = System.nanoTime();
int length = Math.max(s1.length(), s2.length());
double score = ((double) calculateDP(s1, s2)) / length;
long end = System.nanoTime();
double runtime = ((double) ((end - start) / 1000) / 1000d);
return String.format("[%02.3fus] %.02f => (%s;%s) ", runtime, score, s1, s2);
}
public static void main(String[] args) {
System.out.println(measureCalculation("car", "carpet"));
System.out.println(measureCalculation("java", "Javascript"));
System.out.println(measureCalculation("roomkaas", "slagroom"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment