Skip to content

Instantly share code, notes, and snippets.

@Exerosis
Created March 8, 2018 04:26
Show Gist options
  • Select an option

  • Save Exerosis/ecdca8fa22cf978c409596f0e2e2690e to your computer and use it in GitHub Desktop.

Select an option

Save Exerosis/ecdca8fa22cf978c409596f0e2e2690e to your computer and use it in GitHub Desktop.
public static int LCSDistance(@NotNull String first, @NotNull String second) {
int m = first.length();
int n = second.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (first.charAt(i - 1) == second.charAt(j - 1)) {
dp[i][j] = 1 + dp[i - 1][j - 1];
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
public static double levenshteinDistance(@NotNull String first, @NotNull String second) {
final int sLen = first.length(), tLen = second.length();
if (sLen == 0) {
return tLen;
}
if (tLen == 0) {
return sLen;
}
int[] costsPrev = new int[sLen + 1];
int[] costs = new int[sLen + 1];
int[] tmpArr;
int sIndex, tIndex;
int cost;
char tIndexChar;
for (sIndex = 0; sIndex <= sLen; sIndex++)
costsPrev[sIndex] = sIndex;
for (tIndex = 1; tIndex <= tLen; tIndex++) {
tIndexChar = second.charAt(tIndex - 1);
costs[0] = tIndex;
for (sIndex = 1; sIndex <= sLen; sIndex++) {
cost = (first.charAt(sIndex - 1) == tIndexChar) ? 0 : 1;
costs[sIndex] = Math.min(Math.min(costs[sIndex - 1] + 1,
costsPrev[sIndex] + 1),
costsPrev[sIndex - 1] + cost);
}
tmpArr = costsPrev;
costsPrev = costs;
costs = tmpArr;
}
return costsPrev[sLen] / (double) max(first.length(), second.length());
}
public static <Type> Type closest(@NotNull String query, @NotNull Collection<Type> values) {
return closest(query, values, Object::toString);
}
public static <Type> Type closest(@NotNull String query, @NotNull Collection<Type> values, @NotNull Function<Type, String> mapper) {
return values.stream()
.sorted(Comparator.<Type>comparingDouble(value -> levenshteinDistance(mapper.apply(value), query))
.thenComparingDouble(value -> (double) LCSDistance(mapper.apply(value), query)))
.findFirst()
.orElseThrow(NoSuchElementException::new);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment