net.intelie.pipes.util.Levenshtein Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pipes-api Show documentation
Show all versions of pipes-api Show documentation
Intelie Pipes' API classes and interfaces
package net.intelie.pipes.util;
import net.intelie.pipes.PipeException;
import java.util.Locale;
public abstract class Levenshtein {
public static int distance(String a, String b) {
int[] A = new int[b.length() + 1], B = new int[b.length() + 1];
for (int i = 0; i <= b.length(); i++) {
A[i] = i;
}
for (int i = 1; i <= a.length(); i++) {
int[] T = B;
B = A;
A = T;
A[0] = i;
for (int j = 1; j <= b.length(); j++) {
if (a.charAt(i - 1) == b.charAt(j - 1))
A[j] = B[j - 1];
else
A[j] = Math.min(A[j - 1], Math.min(B[j - 1], B[j])) + 1;
}
}
return A[b.length()];
}
public static String closest(String a, Iterable options) {
int bestv = Integer.MAX_VALUE;
String bests = null;
for (String option : options) {
int v = distance(a, option);
if (v < bestv) {
bestv = v;
bests = option;
}
}
return bests;
}
public static PipeException makeExc(String name, Iterable options, String format) {
String closest = Levenshtein.closest(name, options);
return new PipeException(format, name, (closest != null ?
String.format((Locale) null, " Did you mean '%s'?", closest) : ""));
}
}