forked from veeqo/ups-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Replace levenshtein with ruby implementation
- Loading branch information
1 parent
8ee1765
commit 1ace47d
Showing
4 changed files
with
29 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
def levenshtein_distance(str1, str2) | ||
# Create a 2D array to hold distances | ||
rows = str1.length + 1 | ||
cols = str2.length + 1 | ||
dp = Array.new(rows) { Array.new(cols, 0) } | ||
|
||
# Initialize base cases | ||
(0...rows).each { |i| dp[i][0] = i } | ||
(0...cols).each { |j| dp[0][j] = j } | ||
|
||
# Fill the matrix | ||
(1...rows).each do |i| | ||
(1...cols).each do |j| | ||
if str1[i - 1] == str2[j - 1] | ||
dp[i][j] = dp[i - 1][j - 1] # No cost if characters are the same | ||
else | ||
dp[i][j] = [ | ||
dp[i - 1][j], # Deletion | ||
dp[i][j - 1], # Insertion | ||
dp[i - 1][j - 1] # Substitution | ||
].min + 1 | ||
end | ||
end | ||
end | ||
|
||
# The bottom-right cell contains the result | ||
dp[rows - 1][cols - 1] | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters