From f460c2adf8223fdff2eaa039af8781bcba11e587 Mon Sep 17 00:00:00 2001 From: Luqman Aden Date: Sun, 24 Feb 2013 20:44:01 -0800 Subject: [PATCH] Move levenshtein distance fn to core::str. --- src/libcore/str.rs | 34 ++++++++++++++++++++++++++++++++ src/librustc/middle/resolve.rs | 36 +--------------------------------- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 3c15a89081d..92e980e34d0 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -590,6 +590,40 @@ pub fn unshift_char(s: &mut ~str, ch: char) { result } +/// Levenshtein Distance between two strings +pub fn levdistance(s: &str, t: &str) -> uint { + + let slen = str::len(s); + let tlen = str::len(t); + + if slen == 0 { return tlen; } + if tlen == 0 { return slen; } + + let mut dcol = vec::from_fn(tlen + 1, |x| x); + + for str::each_chari(s) |i, sc| { + + let mut current = i; + dcol[0] = current + 1; + + for str::each_chari(t) |j, tc| { + + let mut next = dcol[j + 1]; + + if sc == tc { + dcol[j + 1] = current; + } else { + dcol[j + 1] = ::cmp::min(current, next); + dcol[j + 1] = ::cmp::min(dcol[j + 1], dcol[j]) + 1; + } + + current = next; + } + } + + return dcol[tlen]; +} + /** * Splits a string into a vector of the substrings separated by LF ('\n') */ diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 3db328ceb91..3f1e4dca3a1 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -4830,44 +4830,10 @@ fn find_best_match_for_name(@mut self, name: &str) -> Option<~str> { } } - // Levenshtein Distance between two strings - fn distance(s: &str, t: &str) -> uint { - - let slen = str::len(s); - let tlen = str::len(t); - - if slen == 0 { return tlen; } - if tlen == 0 { return slen; } - - let mut dcol = vec::from_fn(tlen + 1, |x| x); - - for str::each_chari(s) |i, sc| { - - let mut current = i; - dcol[0] = current + 1; - - for str::each_chari(t) |j, tc| { - - let mut next = dcol[j + 1]; - - if sc == tc { - dcol[j + 1] = current; - } else { - dcol[j + 1] = cmp::min(current, next); - dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1; - } - - current = next; - } - } - - return dcol[tlen]; - } - let mut smallest = 0; for vec::eachi(maybes) |i, &other| { - values[i] = distance(name, other); + values[i] = str::levdistance(name, other); if values[i] <= values[smallest] { smallest = i;