Skip to content

Commit 79f036a

Browse files
LorgeNEirik Lorgen Tanberg
andauthored
[TEXT-235] Add Damerau-Levenshtein distance (#687)
* [TEXT-235] Implement Damerau-Levenshtein distance * Fix comment formatting * Fix style and spotbugs --------- Co-authored-by: Eirik Lorgen Tanberg <[email protected]>
1 parent 4f35559 commit 79f036a

File tree

2 files changed

+546
-0
lines changed

2 files changed

+546
-0
lines changed
Lines changed: 326 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,326 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* https://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package org.apache.commons.text.similarity;
18+
19+
/**
20+
* An algorithm for measuring the difference between two character sequences using the
21+
* <a href="https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance">Damerau-Levenshtein Distance</a>.
22+
*
23+
* <p>
24+
* This is the number of changes needed to change one sequence into another, where each change is a single character
25+
* modification (deletion, insertion, substitution, or transposition of two adjacent characters).
26+
* </p>
27+
*
28+
* @see <a href="https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance">Damerau-Levenshtein Distance on Wikipedia</a>
29+
* @since 1.15.0
30+
*/
31+
public class DamerauLevenshteinDistance implements EditDistance<Integer> {
32+
33+
/**
34+
* Utility function to ensure distance is valid according to threshold.
35+
*
36+
* @param distance The distance value
37+
* @param threshold The threshold value
38+
* @return The distance value, or {@code -1} if distance is greater than threshold
39+
*/
40+
private static int clampDistance(final int distance, final int threshold) {
41+
return distance > threshold ? -1 : distance;
42+
}
43+
44+
/**
45+
* Finds the Damerau-Levenshtein distance between two CharSequences if it's less than or equal to a given threshold.
46+
*
47+
* @param left the first SimilarityInput, must not be null.
48+
* @param right the second SimilarityInput, must not be null.
49+
* @param threshold the target threshold, must not be negative.
50+
* @return result distance, or -1 if distance exceeds threshold
51+
*/
52+
private static <E> int limitedCompare(SimilarityInput<E> left, SimilarityInput<E> right, final int threshold) {
53+
if (left == null || right == null) {
54+
throw new IllegalArgumentException("Left/right inputs must not be null");
55+
}
56+
57+
if (threshold < 0) {
58+
throw new IllegalArgumentException("Threshold can not be negative");
59+
}
60+
61+
// Implementation based on https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance
62+
63+
int leftLength = left.length();
64+
int rightLength = right.length();
65+
66+
if (leftLength == 0) {
67+
return clampDistance(rightLength, threshold);
68+
}
69+
70+
if (rightLength == 0) {
71+
return clampDistance(leftLength, threshold);
72+
}
73+
74+
// Inspired by LevenshteinDistance impl; swap the input strings to consume less memory
75+
if (rightLength > leftLength) {
76+
final SimilarityInput<E> tmp = left;
77+
left = right;
78+
right = tmp;
79+
leftLength = rightLength;
80+
rightLength = right.length();
81+
}
82+
83+
// If the difference between the lengths of the strings is greater than the threshold, we must at least do
84+
// threshold operations so we can return early
85+
if (leftLength - rightLength > threshold) {
86+
return -1;
87+
}
88+
89+
// Use three arrays of minimum possible size to reduce memory usage. This avoids having to create a 2D
90+
// array of size leftLength * rightLength
91+
int[] curr = new int[rightLength + 1];
92+
int[] prev = new int[rightLength + 1];
93+
int[] prevPrev = new int[rightLength + 1];
94+
int[] temp; // Temp variable use to shuffle arrays at the end of each iteration
95+
96+
int rightIndex, leftIndex, cost, minCost;
97+
98+
// Changing empty sequence to [0..i] requires i insertions
99+
for (rightIndex = 0; rightIndex <= rightLength; rightIndex++) {
100+
prev[rightIndex] = rightIndex;
101+
}
102+
103+
// Calculate how many operations it takes to change right[0..rightIndex] into left[0..leftIndex]
104+
// For each iteration
105+
// - curr[i] contains the cost of changing right[0..i] into left[0..leftIndex]
106+
// (computed in current iteration)
107+
// - prev[i] contains the cost of changing right[0..i] into left[0..leftIndex - 1]
108+
// (computed in previous iteration)
109+
// - prevPrev[i] contains the cost of changing right[0..i] into left[0..leftIndex - 2]
110+
// (computed in iteration before previous)
111+
for (leftIndex = 1; leftIndex <= leftLength; leftIndex++) {
112+
// For right[0..0] we must insert leftIndex characters, which means the cost is always leftIndex
113+
curr[0] = leftIndex;
114+
115+
minCost = Integer.MAX_VALUE;
116+
117+
for (rightIndex = 1; rightIndex <= rightLength; rightIndex++) {
118+
cost = (left.at(leftIndex - 1) == right.at(rightIndex - 1)) ? 0 : 1;
119+
120+
// Select cheapest operation
121+
curr[rightIndex] = Math.min(
122+
Math.min(
123+
prev[rightIndex] + 1, // Delete current character
124+
curr[rightIndex - 1] + 1 // Insert current character
125+
),
126+
prev[rightIndex - 1] + cost // Replace (or no cost if same character)
127+
);
128+
129+
// Check if adjacent characters are the same -> transpose if cheaper
130+
if (leftIndex > 1
131+
&& rightIndex > 1
132+
&& left.at(leftIndex - 1) == right.at(rightIndex - 2)
133+
&& left.at(leftIndex - 2) == right.at(rightIndex - 1)) {
134+
// Use cost here, to properly handle two subsequent equal letters
135+
curr[rightIndex] = Math.min(curr[rightIndex], prevPrev[rightIndex - 2] + cost);
136+
}
137+
138+
minCost = Math.min(curr[rightIndex], minCost);
139+
}
140+
141+
// If there was no total cost for this entire iteration to transform right to left[0..leftIndex], there
142+
// can not be a way to do it below threshold. This is because we have no way to reduce the overall cost
143+
// in later operations.
144+
if (minCost > threshold) {
145+
return -1;
146+
}
147+
148+
// Rotate arrays for next iteration
149+
temp = prevPrev;
150+
prevPrev = prev;
151+
prev = curr;
152+
curr = temp;
153+
}
154+
155+
// Prev contains the value computed in the latest iteration
156+
return clampDistance(prev[rightLength], threshold);
157+
}
158+
159+
/**
160+
* Finds the Damerau-Levenshtein distance between two inputs using optimal string alignment.
161+
*
162+
* @param left the first CharSequence, must not be null.
163+
* @param right the second CharSequence, must not be null.
164+
* @return result distance.
165+
* @throws IllegalArgumentException if either CharSequence input is {@code null}.
166+
*/
167+
private static <E> int unlimitedCompare(SimilarityInput<E> left, SimilarityInput<E> right) {
168+
if (left == null || right == null) {
169+
throw new IllegalArgumentException("Left/right inputs must not be null");
170+
}
171+
172+
/*
173+
* Implementation based on https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance
174+
*/
175+
176+
int leftLength = left.length();
177+
int rightLength = right.length();
178+
179+
if (leftLength == 0) {
180+
return rightLength;
181+
}
182+
183+
if (rightLength == 0) {
184+
return leftLength;
185+
}
186+
187+
// Inspired by LevenshteinDistance impl; swap the input strings to consume less memory
188+
if (rightLength > leftLength) {
189+
final SimilarityInput<E> tmp = left;
190+
left = right;
191+
right = tmp;
192+
leftLength = rightLength;
193+
rightLength = right.length();
194+
}
195+
196+
// Use three arrays of minimum possible size to reduce memory usage. This avoids having to create a 2D
197+
// array of size leftLength * rightLength
198+
int[] curr = new int[rightLength + 1];
199+
int[] prev = new int[rightLength + 1];
200+
int[] prevPrev = new int[rightLength + 1];
201+
int[] temp; // Temp variable use to shuffle arrays at the end of each iteration
202+
203+
int rightIndex, leftIndex, cost;
204+
205+
// Changing empty sequence to [0..i] requires i insertions
206+
for (rightIndex = 0; rightIndex <= rightLength; rightIndex++) {
207+
prev[rightIndex] = rightIndex;
208+
}
209+
210+
// Calculate how many operations it takes to change right[0..rightIndex] into left[0..leftIndex]
211+
// For each iteration
212+
// - curr[i] contains the cost of changing right[0..i] into left[0..leftIndex]
213+
// (computed in current iteration)
214+
// - prev[i] contains the cost of changing right[0..i] into left[0..leftIndex - 1]
215+
// (computed in previous iteration)
216+
// - prevPrev[i] contains the cost of changing right[0..i] into left[0..leftIndex - 2]
217+
// (computed in iteration before previous)
218+
for (leftIndex = 1; leftIndex <= leftLength; leftIndex++) {
219+
// For right[0..0] we must insert leftIndex characters, which means the cost is always leftIndex
220+
curr[0] = leftIndex;
221+
222+
for (rightIndex = 1; rightIndex <= rightLength; rightIndex++) {
223+
cost = (left.at(leftIndex - 1) == right.at(rightIndex - 1)) ? 0 : 1;
224+
225+
// Select cheapest operation
226+
curr[rightIndex] = Math.min(
227+
Math.min(
228+
prev[rightIndex] + 1, // Delete current character
229+
curr[rightIndex - 1] + 1 // Insert current character
230+
),
231+
prev[rightIndex - 1] + cost // Replace (or no cost if same character)
232+
);
233+
234+
// Check if adjacent characters are the same -> transpose if cheaper
235+
if (leftIndex > 1
236+
&& rightIndex > 1
237+
&& left.at(leftIndex - 1) == right.at(rightIndex - 2)
238+
&& left.at(leftIndex - 2) == right.at(rightIndex - 1)) {
239+
// Use cost here, to properly handle two subsequent equal letters
240+
curr[rightIndex] = Math.min(curr[rightIndex], prevPrev[rightIndex - 2] + cost);
241+
}
242+
}
243+
244+
// Rotate arrays for next iteration
245+
temp = prevPrev;
246+
prevPrev = prev;
247+
prev = curr;
248+
curr = temp;
249+
}
250+
251+
// Prev contains the value computed in the latest iteration
252+
return prev[rightLength];
253+
}
254+
255+
/**
256+
* Threshold.
257+
*/
258+
private final Integer threshold;
259+
260+
/**
261+
* Constructs a default instance that uses a version of the algorithm that does not use a threshold parameter.
262+
*/
263+
public DamerauLevenshteinDistance() {
264+
this(null);
265+
}
266+
267+
/**
268+
* Constructs a new instance. If the threshold is not null, distance calculations will be limited to a maximum length.
269+
* If the threshold is null, the unlimited version of the algorithm will be used.
270+
*
271+
* @param threshold If this is null then distances calculations will not be limited. This may not be negative.
272+
*/
273+
public DamerauLevenshteinDistance(final Integer threshold) {
274+
if (threshold != null && threshold < 0) {
275+
throw new IllegalArgumentException("Threshold must not be negative");
276+
}
277+
this.threshold = threshold;
278+
}
279+
280+
/**
281+
* Computes the Damerau-Levenshtein distance between two Strings.
282+
*
283+
* <p>
284+
* A higher score indicates a greater distance.
285+
* </p>
286+
*
287+
* @param left the first input, must not be null.
288+
* @param right the second input, must not be null.
289+
* @return result distance, or -1 if threshold is exceeded.
290+
* @throws IllegalArgumentException if either String input {@code null}.
291+
*/
292+
@Override
293+
public Integer apply(final CharSequence left, final CharSequence right) {
294+
return apply(SimilarityInput.input(left), SimilarityInput.input(right));
295+
}
296+
297+
/**
298+
* Computes the Damerau-Levenshtein distance between two inputs.
299+
*
300+
* <p>
301+
* A higher score indicates a greater distance.
302+
* </p>
303+
*
304+
* @param <E> The type of similarity score unit.
305+
* @param left the first input, must not be null.
306+
* @param right the second input, must not be null.
307+
* @return result distance, or -1 if threshold is exceeded.
308+
* @throws IllegalArgumentException if either String input {@code null}.
309+
* @since 1.13.0
310+
*/
311+
public <E> Integer apply(final SimilarityInput<E> left, final SimilarityInput<E> right) {
312+
if (threshold != null) {
313+
return limitedCompare(left, right, threshold);
314+
}
315+
return unlimitedCompare(left, right);
316+
}
317+
318+
/**
319+
* Gets the distance threshold.
320+
*
321+
* @return The distance threshold.
322+
*/
323+
public Integer getThreshold() {
324+
return threshold;
325+
}
326+
}

0 commit comments

Comments
 (0)