Skip to content
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 @@ -93,11 +93,19 @@ public final double distance(final String s1, final String s2,
}

if (s1.length() == 0) {
return s2.length();
double cost = 0;
for (int i = 0; i < s2.length(); i++) {
cost += insertionCost(s2.charAt(i));
}
return cost;
}

if (s2.length() == 0) {
return s1.length();
double cost = 0;
for (int i = 0; i < s1.length(); i++) {
cost += deletionCost(s1.charAt(i));
}
return cost;
}

// create two work vectors of floating point (i.e. weighted) distances
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,28 @@ public double insertionCost(char c) {

NullEmptyTests.testDistance(instance);
}

@Test
public void emptyStringsUseCharacterInsertionCosts() {
WeightedLevenshtein distance = weightedDistance();
assertEquals(2.5, distance.distance("", "ab"), 0.000001);
assertEquals(2.5, distance.distance("", "ab", Double.MAX_VALUE), 0.000001);
}

@Test
public void emptyStringsUseCharacterDeletionCosts() {
WeightedLevenshtein distance = weightedDistance();
assertEquals(4.75, distance.distance("ab", ""), 0.000001);
assertEquals(4.75, distance.distance("ab", "", Double.MAX_VALUE), 0.000001);
}

private WeightedLevenshtein weightedDistance() {
return new WeightedLevenshtein(new CharacterSubstitutionInterface() {
public double cost(char a, char b) { return 1.0; }
}, new CharacterInsDelInterface() {
public double insertionCost(char c) { return c == 'a' ? 0.5 : 2.0; }
public double deletionCost(char c) { return c == 'a' ? 0.75 : 4.0; }
});
}

}