From b0ae3aafc3033dde12b6d411b0d54c1089f5cf88 Mon Sep 17 00:00:00 2001 From: Navaneethan Date: Tue, 17 Nov 2026 17:05:40 +0530 Subject: [PATCH] Fix Levenshtein distance for empty strings --- string_manipulation/levenshtein.r | 84 +++++++++++++++++++++++-------- 1 file changed, 62 insertions(+), 22 deletions(-) diff --git a/string_manipulation/levenshtein.r b/string_manipulation/levenshtein.r index 73ac2bd3..c383d2c5 100644 --- a/string_manipulation/levenshtein.r +++ b/string_manipulation/levenshtein.r @@ -1,38 +1,78 @@ # Levenshtein Distance in R -# Calculates minimum number of edits (insert, delete, replace) -# to convert one string into another and prints the distance. +# +# Calculates the minimum number of edits needed to transform +# one string into another. +# +# Allowed operations: +# - insertion +# - deletion +# - substitution levenshtein_distance <- function(s1, s2) { + if (length(s1) != 1 || length(s2) != 1) { + stop("s1 and s2 must each contain exactly one string") + } + + s1 <- as.character(s1) + s2 <- as.character(s2) + n <- nchar(s1) m <- nchar(s2) - # Initialize DP matrix - dp <- matrix(0, nrow = n + 1, ncol = m + 1) + dp <- matrix( + 0, + nrow = n + 1, + ncol = m + 1 + ) - for (i in 0:n) dp[i + 1, 1] <- i - for (j in 0:m) dp[1, j + 1] <- j + for (i in 0:n) { + dp[i + 1, 1] <- i + } - # Fill DP table - for (i in 1:n) { - for (j in 1:m) { - if (substr(s1, i, i) == substr(s2, j, j)) { - dp[i + 1, j + 1] <- dp[i, j] - } else { + for (j in 0:m) { + dp[1, j + 1] <- j + } + + # Avoid 1:0 when either string is empty. + if (n > 0 && m > 0) { + for (i in seq_len(n)) { + for (j in seq_len(m)) { + substitution_cost <- if ( + substr(s1, i, i) == substr(s2, j, j) + ) { + 0 + } else { + 1 + } + dp[i + 1, j + 1] <- min( - dp[i, j + 1] + 1, # Deletion - dp[i + 1, j] + 1, # Insertion - dp[i, j] + 1 # Substitution + dp[i, j + 1] + 1, + dp[i + 1, j] + 1, + dp[i, j] + substitution_cost ) } } } - return(dp[n + 1, m + 1]) + dp[n + 1, m + 1] } -# Interactive input -s1 <- tolower(readline("Enter first string: ")) -s2 <- tolower(readline("Enter second string: ")) - -distance <- levenshtein_distance(s1, s2) -cat("Levenshtein distance between '", s1, "' and '", s2, "' is:", distance, "\n") \ No newline at end of file +# Interactive example. +# This does not run when the file is sourced for testing. +if (interactive()) { + s1 <- tolower(readline("Enter first string: ")) + s2 <- tolower(readline("Enter second string: ")) + + distance <- levenshtein_distance(s1, s2) + + cat( + "Levenshtein distance between '", + s1, + "' and '", + s2, + "' is: ", + distance, + "\n", + sep = "" + ) +} \ No newline at end of file