Skip to content

Commit 92b2981

Browse files
committed
added levenshtein
1 parent 1887b93 commit 92b2981

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

levenshtein.R

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Levenshtein Distance in R
2+
# Calculates minimum number of edits (insert, delete, replace)
3+
# to convert one string into another and prints the distance.
4+
5+
levenshtein_distance <- function(s1, s2) {
6+
n <- nchar(s1)
7+
m <- nchar(s2)
8+
9+
# Initialize DP matrix
10+
dp <- matrix(0, nrow = n + 1, ncol = m + 1)
11+
12+
for (i in 0:n) dp[i + 1, 1] <- i
13+
for (j in 0:m) dp[1, j + 1] <- j
14+
15+
# Fill DP table
16+
for (i in 1:n) {
17+
for (j in 1:m) {
18+
if (substr(s1, i, i) == substr(s2, j, j)) {
19+
dp[i + 1, j + 1] <- dp[i, j]
20+
} else {
21+
dp[i + 1, j + 1] <- min(
22+
dp[i, j + 1] + 1, # Deletion
23+
dp[i + 1, j] + 1, # Insertion
24+
dp[i, j] + 1 # Substitution
25+
)
26+
}
27+
}
28+
}
29+
30+
return(dp[n + 1, m + 1])
31+
}
32+
33+
# Interactive input
34+
s1 <- tolower(readline("Enter first string: "))
35+
s2 <- tolower(readline("Enter second string: "))
36+
37+
distance <- levenshtein_distance(s1, s2)
38+
cat("Levenshtein distance between '", s1, "' and '", s2, "' is:"distance"\n")

0 commit comments

Comments
 (0)