NPL:RUST: MIN-EDIT-DISTANCE - ALGORITHM
The Algorithm:
Rust implementation:
How to compile:
use std::cmp::min;
fn min_edit_distance(source: &str, target: &str) -> usize {
let n = source.chars().count();
let m = target.chars().count();
let mut d = vec![vec![0; m + 1]; n + 1];
for i in 0..=n {
d[i][0] = i;
}
for j in 0..=m {
d[0][j] = j;
}
for i in 1..=n {
for j in 1..=m {
let cost = if source.chars().nth(i - 1) == target.chars().nth(j - 1) {
0
} else {
1
};
d[i][j] = min(
d[i - 1][j] + 1,
min(d[i][j - 1] + 1, d[i - 1][j - 1] + cost),
);
}
}
d[n][m]
}
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
println!("Usage: {} <source> <target>", args[0]);
return;
}
let source = &args[1];
let target = &args[2];
let distance = min_edit_distance(source, target);
println!("The minimum edit distance between '{}' and '{}' is {}.", source, target, distance);
}
How to compile:
- Create a new project in rust: cargo new mind_dist
- edit src/main.rs and paste the code
- build the program cargo build --release
- use the program target/mind_dist <source> <target>
Comentarios
Publicar un comentario