Skip to content

Commit

Permalink
Replace levenshtein with ruby implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
mikefranken committed Dec 19, 2024
1 parent 8ee1765 commit 1ace47d
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 7 deletions.
1 change: 0 additions & 1 deletion Gemfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
source 'http://rubygems.org'
gem "levenshtein-ffi", git: "https://github.com/zilverline/levenshtein-ffi.git"
gemspec

group :development, :test do
Expand Down
4 changes: 0 additions & 4 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ PATH
ups-ruby (0.17.1)
excon (~> 0.45, >= 0.45.3)
insensitive_hash (~> 0.3.3)
levenshtein-ffi (~> 1.1)
ox (~> 2.2, >= 2.2.0)

GEM
Expand All @@ -15,12 +14,9 @@ GEM
simplecov (<= 0.13)
docile (1.1.5)
excon (0.110.0)
ffi (1.16.3)
insensitive_hash (0.3.3)
json (2.7.2)
language_server-protocol (3.17.0.3)
levenshtein-ffi (1.1.0)
ffi (~> 1.9)
minitest (5.22.3)
ox (2.14.18)
parallel (1.24.0)
Expand Down
28 changes: 28 additions & 0 deletions lib/levenshtein.rb
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
3 changes: 1 addition & 2 deletions lib/ups/data.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# frozen_string_literal: true

require 'levenshtein'

module UPS
Expand Down Expand Up @@ -33,7 +32,7 @@ def ie_state_matcher(match_string)

normalized_string = ie_state_normalizer string_normalizer match_string
counties_with_distances = IE_COUNTIES.map do |county|
[county, Levenshtein.distance(county.downcase, normalized_string)]
[county, levenshtein_distance(county.downcase, normalized_string)]
end
counties_with_distances_hash = Hash[*counties_with_distances.flatten]
counties_with_distances_hash.min_by { |_k, v| v }[0]
Expand Down

0 comments on commit 1ace47d

Please sign in to comment.