Skip to content

Commit

Permalink
Remove kruft, make more idiomatic
Browse files Browse the repository at this point in the history
  • Loading branch information
sammysheep committed Jan 13, 2025
1 parent 655d7e7 commit c08ef04
Showing 1 changed file with 16 additions and 32 deletions.
48 changes: 16 additions & 32 deletions levenshtein/rust/code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,54 +3,38 @@ use std::env;
/// Calculates the Levenshtein distance between two strings using Wagner-Fischer algorithm
/// Space Complexity: O(min(m,n)) - only uses two rows instead of full matrix
/// Time Complexity: O(m*n) where m and n are the lengths of the input strings
fn levenshtein_distance(s1: &str, s2: &str) -> usize {
// Early termination checks
if s1 == s2 {
return 0;
}
if s1.is_empty() {
return s2.len();
}
if s2.is_empty() {
return s1.len();
}

// Convert to bytes for faster access
let s1_bytes = s1.as_bytes();
let s2_bytes = s2.as_bytes();

// Make s1 the shorter string for space optimization
let (s1_bytes, s2_bytes) = if s1_bytes.len() > s2_bytes.len() {
(s2_bytes, s1_bytes)
fn levenshtein_distance(s1: &[u8], s2: &[u8]) -> usize {
let (s1_bytes, s2_bytes) = if s1.len() > s2.len() {
(s2, s1)
} else {
(s1_bytes, s2_bytes)
(s1, s2)
};

let m = s1_bytes.len();
let n = s2_bytes.len();

// Use two rows instead of full matrix for space optimization
let mut prev_row = Vec::with_capacity(m + 1);
let mut curr_row = Vec::with_capacity(m + 1);

// Initialize first row
prev_row.extend(0..=m);
curr_row.resize(m + 1, 0);
let mut prev_row = vec![0; m + 1];
let mut curr_row = vec![0; m + 1];

// Main computation loop
for j in 1..=n {
curr_row[0] = j;

for i in 1..=m {
let cost = if s1_bytes[i - 1] == s2_bytes[j - 1] { 0 } else { 1 };

let cost = if s1_bytes[i - 1] == s2_bytes[j - 1] {
0
} else {
1
};

// Calculate minimum of three operations
curr_row[i] = std::cmp::min(
std::cmp::min(
prev_row[i] + 1, // deletion
curr_row[i - 1] + 1, // insertion
prev_row[i] + 1, // deletion
curr_row[i - 1] + 1, // insertion
),
prev_row[i - 1] + cost // substitution
prev_row[i - 1] + cost, // substitution
);
}

Expand All @@ -76,7 +60,7 @@ fn main() {
for i in 0..args.len() {
for j in 0..args.len() {
if i != j {
let distance = levenshtein_distance(&args[i], &args[j]);
let distance = levenshtein_distance(args[i].as_bytes(), args[j].as_bytes());
if let Some(current_min) = min_distance {
if distance < current_min {
min_distance = Some(distance);
Expand Down

0 comments on commit c08ef04

Please sign in to comment.