1pub fn levenshtein_distance(a: &str, b: &str) -> usize {
21 let a_len = a.chars().count();
22 let b_len = b.chars().count();
23
24 if a_len == 0 {
25 return b_len;
26 }
27 if b_len == 0 {
28 return a_len;
29 }
30
31 let (short, long, short_len) = if a_len < b_len {
33 (a, b, a_len)
34 } else {
35 (b, a, b_len)
36 };
37
38 let mut prev_row: Vec<usize> = (0..=short_len).collect();
40 let mut curr_row: Vec<usize> = vec![0; short_len + 1];
41
42 let short_chars: Vec<char> = short.chars().collect();
43
44 for (i, long_char) in long.chars().enumerate() {
45 curr_row[0] = i + 1;
46
47 for (j, &short_char) in short_chars.iter().enumerate() {
48 let cost = if long_char == short_char { 0 } else { 1 };
49
50 curr_row[j + 1] = std::cmp::min(
51 std::cmp::min(
52 curr_row[j] + 1, prev_row[j + 1] + 1, ),
55 prev_row[j] + cost, );
57 }
58
59 std::mem::swap(&mut prev_row, &mut curr_row);
60 }
61
62 prev_row[short_len]
63}
64
65pub fn suggest_similar(target: &str, candidates: &[String], threshold: usize) -> Vec<String> {
91 let mut matches: Vec<(String, usize)> = candidates
92 .iter()
93 .filter_map(|candidate| {
94 let distance = levenshtein_distance(target, candidate);
95 if distance <= threshold {
96 Some((candidate.clone(), distance))
97 } else {
98 None
99 }
100 })
101 .collect();
102
103 matches.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
105
106 matches.into_iter().map(|(s, _)| s).collect()
107}
108
109pub fn find_best_match(target: &str, candidates: &[String], threshold: usize) -> Option<String> {
134 suggest_similar(target, candidates, threshold)
135 .into_iter()
136 .next()
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142
143 #[test]
144 fn test_levenshtein_distance_identical() {
145 assert_eq!(levenshtein_distance("hello", "hello"), 0);
146 assert_eq!(levenshtein_distance("", ""), 0);
147 }
148
149 #[test]
150 fn test_levenshtein_distance_empty() {
151 assert_eq!(levenshtein_distance("", "abc"), 3);
152 assert_eq!(levenshtein_distance("abc", ""), 3);
153 }
154
155 #[test]
156 fn test_levenshtein_distance_single_char() {
157 assert_eq!(levenshtein_distance("a", "b"), 1);
158 assert_eq!(levenshtein_distance("a", "a"), 0);
159 }
160
161 #[test]
162 fn test_levenshtein_distance_classic_examples() {
163 assert_eq!(levenshtein_distance("kitten", "sitting"), 3);
164 assert_eq!(levenshtein_distance("Saturday", "Sunday"), 3);
165 assert_eq!(levenshtein_distance("rosettacode", "raisethysword"), 8);
166 }
167
168 #[test]
169 fn test_levenshtein_distance_case_sensitive() {
170 assert_eq!(levenshtein_distance("Hello", "hello"), 1);
171 assert_eq!(levenshtein_distance("HELLO", "hello"), 5);
172 }
173
174 #[test]
175 fn test_suggest_similar_exact_match() {
176 let candidates = vec!["Warehouse".to_string(), "Factory".to_string()];
177 let suggestions = suggest_similar("Warehouse", &candidates, 2);
178 assert_eq!(suggestions, vec!["Warehouse"]);
179 }
180
181 #[test]
182 fn test_suggest_similar_typo() {
183 let candidates = vec![
184 "Warehouse".to_string(),
185 "Factory".to_string(),
186 "Supplier".to_string(),
187 ];
188 let suggestions = suggest_similar("Warehous", &candidates, 2);
189 assert_eq!(suggestions, vec!["Warehouse"]);
190 }
191
192 #[test]
193 fn test_suggest_similar_multiple_matches() {
194 let candidates = vec![
195 "Warehouse".to_string(),
196 "Warehouses".to_string(),
197 "Factory".to_string(),
198 ];
199 let suggestions = suggest_similar("Warehous", &candidates, 2);
200 assert!(suggestions.contains(&"Warehouse".to_string()));
202 assert!(suggestions.contains(&"Warehouses".to_string()));
203 }
204
205 #[test]
206 fn test_suggest_similar_no_matches() {
207 let candidates = vec!["Warehouse".to_string(), "Factory".to_string()];
208 let suggestions = suggest_similar("XYZ", &candidates, 2);
209 assert_eq!(suggestions.len(), 0);
210 }
211
212 #[test]
213 fn test_suggest_similar_sorted_by_distance() {
214 let candidates = vec![
215 "Warehouse".to_string(),
216 "Warehouses".to_string(),
217 "Ware".to_string(),
218 ];
219 let suggestions = suggest_similar("War", &candidates, 5);
220 assert_eq!(suggestions, vec!["Ware"]);
223 }
224
225 #[test]
226 fn test_find_best_match() {
227 let candidates = vec![
228 "Warehouse".to_string(),
229 "Factory".to_string(),
230 "Supplier".to_string(),
231 ];
232 assert_eq!(
233 find_best_match("Warehous", &candidates, 2),
234 Some("Warehouse".to_string())
235 );
236 assert_eq!(find_best_match("XYZ", &candidates, 2), None);
237 }
238
239 #[test]
240 fn test_find_best_match_tie_alphabetical() {
241 let candidates = vec!["Apple".to_string(), "Apples".to_string()];
242 let result = find_best_match("Appl", &candidates, 2);
244 assert_eq!(result, Some("Apple".to_string()));
245 }
246
247 #[test]
248 fn test_unicode_support() {
249 assert_eq!(levenshtein_distance("café", "cafe"), 1);
250 assert_eq!(levenshtein_distance("北京", "北京"), 0);
251 assert_eq!(levenshtein_distance("北京", "上海"), 2);
252 }
253}