Skip to content

Commit

Permalink
Fix: Get rid of duplicate code in diff() and distance() (#15)
Browse files Browse the repository at this point in the history
Fixes #9
  • Loading branch information
notalfredo authored Dec 31, 2022
1 parent fb1eac2 commit 5d35501
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 45 deletions.
12 changes: 1 addition & 11 deletions src/hamming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,7 @@ impl StringDiffAlgorithm for HammingDistance {
}

fn distance<'a>(&self, s1: &'a str, s2: &'a str) -> usize {
if s1.len() != s2.len() {
panic!("Strings must be same length");
} else {
let mut edit_distance: usize = 0;
for i in 0..s1.len() {
if s1.chars().nth(i).unwrap() != s2.chars().nth(i).unwrap() {
edit_distance += 1;
}
}
edit_distance
}
self.diff(s1, s2).len()
}
}

Expand Down
44 changes: 10 additions & 34 deletions src/levenshtein.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,7 @@ impl LevenshteinDistance {

diff_ops
}
}
impl StringDiffAlgorithm for LevenshteinDistance {
fn diff<'a>(&self, s1: &'a str, s2: &'a str) -> Vec<StringDiffOp> {
pub(crate) fn get_operation_matrix(s1: &str, s2: &str) -> Vec<Vec<char>> {
let first_string_len: usize = s1.len();
let second_string_len: usize = s2.len();

Expand Down Expand Up @@ -154,39 +152,17 @@ impl StringDiffAlgorithm for LevenshteinDistance {
); //substitution
}
}

LevenshteinDistance::get_operations(&dir_vector, s2, s1)
dir_vector
}
}
impl StringDiffAlgorithm for LevenshteinDistance {
fn diff<'a>(&self, s1: &'a str, s2: &'a str) -> Vec<StringDiffOp> {
let dir_matrix = LevenshteinDistance::get_operation_matrix(s1, s2);
LevenshteinDistance::get_operations(&dir_matrix, s2, s1)
}
fn distance<'a>(&self, s1: &'a str, s2: &'a str) -> usize {
let first_string_len: usize = s1.len();
let second_string_len: usize = s2.len();

let mut dist_vector = vec![vec![0usize; first_string_len + 1]; second_string_len + 1];

for i in 0..first_string_len + 1 {
dist_vector[0][i] = i;
}

for i in 0..second_string_len + 1 {
dist_vector[i][0] = i;
}

let mut sub_cost: usize = 0;
for i in 1..second_string_len + 1 {
for j in 1..first_string_len + 1 {
if s1.chars().nth(j - 1).unwrap() == s2.chars().nth(i - 1).unwrap() {
sub_cost = 0;
} else {
sub_cost = 1;
}
dist_vector[i][j] = LevenshteinDistance::min_dist(
dist_vector[i - 1][j] + 1,
dist_vector[i][j - 1] + 1,
dist_vector[i - 1][j - 1] + sub_cost,
);
}
}
dist_vector[second_string_len][first_string_len]
let dir_matrix = LevenshteinDistance::get_operation_matrix(s1, s2);
LevenshteinDistance::get_operations(&dir_matrix, s2, s1).len()
}
}

Expand Down

0 comments on commit 5d35501

Please sign in to comment.