Levenshtein distance: Difference between revisions
Content added Content deleted
(Added Wren) |
(→{{header|Rust}}: more concise and efficient initialization of 'matrix') |
||
Line 4,763: | Line 4,763: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
Implementation of the wikipedia algorithm. |
Implementation of the wikipedia algorithm. |
||
{{works with|Rust|1. |
{{works with|Rust|1.45}} |
||
<lang rust>fn main() { |
<lang rust>fn main() { |
||
println!("{}", levenshtein_distance("kitten", "sitting")); |
println!("{}", levenshtein_distance("kitten", "sitting")); |
||
Line 4,769: | Line 4,769: | ||
println!("{}", levenshtein_distance("rosettacode", "raisethysword")); |
println!("{}", levenshtein_distance("rosettacode", "raisethysword")); |
||
} |
} |
||
fn levenshtein_distance(word1: &str, word2: &str) -> usize { |
fn levenshtein_distance(word1: &str, word2: &str) -> usize { |
||
let w1 = word1.chars().collect::<Vec<_>>(); |
let w1 = word1.chars().collect::<Vec<_>>(); |
||
let w2 = word2.chars().collect::<Vec<_>>(); |
let w2 = word2.chars().collect::<Vec<_>>(); |
||
let word1_length = w1.len() + 1; |
let word1_length = w1.len() + 1; |
||
let word2_length = w2.len() + 1; |
let word2_length = w2.len() + 1; |
||
let mut matrix = vec![vec![0]]; |
let mut matrix = vec![vec![0; word1_length]; word2_length]; |
||
for i in 1..word1_length { matrix[0] |
for i in 1..word1_length { matrix[0][i] = i; } |
||
for j in 1..word2_length { matrix |
for j in 1..word2_length { matrix[j][0] = j; } |
||
for j in 1..word2_length { |
for j in 1..word2_length { |
||
for i in 1..word1_length { |
for i in 1..word1_length { |
||
Line 4,791: | Line 4,791: | ||
, matrix[j-1][i-1]) |
, matrix[j-1][i-1]) |
||
}; |
}; |
||
matrix[j] |
matrix[j][i] = x; |
||
} |
} |
||
} |
} |