Skip to content

Commit 1ace47d

Browse files
committed
Replace levenshtein with ruby implementation
1 parent 8ee1765 commit 1ace47d

4 files changed

Lines changed: 29 additions & 7 deletions

File tree

Gemfile

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
source 'http://rubygems.org'
2-
gem "levenshtein-ffi", git: "https://github.com/zilverline/levenshtein-ffi.git"
32
gemspec
43

54
group :development, :test do

Gemfile.lock

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ PATH
44
ups-ruby (0.17.1)
55
excon (~> 0.45, >= 0.45.3)
66
insensitive_hash (~> 0.3.3)
7-
levenshtein-ffi (~> 1.1)
87
ox (~> 2.2, >= 2.2.0)
98

109
GEM
@@ -15,12 +14,9 @@ GEM
1514
simplecov (<= 0.13)
1615
docile (1.1.5)
1716
excon (0.110.0)
18-
ffi (1.16.3)
1917
insensitive_hash (0.3.3)
2018
json (2.7.2)
2119
language_server-protocol (3.17.0.3)
22-
levenshtein-ffi (1.1.0)
23-
ffi (~> 1.9)
2420
minitest (5.22.3)
2521
ox (2.14.18)
2622
parallel (1.24.0)

lib/levenshtein.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
def levenshtein_distance(str1, str2)
2+
# Create a 2D array to hold distances
3+
rows = str1.length + 1
4+
cols = str2.length + 1
5+
dp = Array.new(rows) { Array.new(cols, 0) }
6+
7+
# Initialize base cases
8+
(0...rows).each { |i| dp[i][0] = i }
9+
(0...cols).each { |j| dp[0][j] = j }
10+
11+
# Fill the matrix
12+
(1...rows).each do |i|
13+
(1...cols).each do |j|
14+
if str1[i - 1] == str2[j - 1]
15+
dp[i][j] = dp[i - 1][j - 1] # No cost if characters are the same
16+
else
17+
dp[i][j] = [
18+
dp[i - 1][j], # Deletion
19+
dp[i][j - 1], # Insertion
20+
dp[i - 1][j - 1] # Substitution
21+
].min + 1
22+
end
23+
end
24+
end
25+
26+
# The bottom-right cell contains the result
27+
dp[rows - 1][cols - 1]
28+
end

lib/ups/data.rb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# frozen_string_literal: true
2-
32
require 'levenshtein'
43

54
module UPS
@@ -33,7 +32,7 @@ def ie_state_matcher(match_string)
3332

3433
normalized_string = ie_state_normalizer string_normalizer match_string
3534
counties_with_distances = IE_COUNTIES.map do |county|
36-
[county, Levenshtein.distance(county.downcase, normalized_string)]
35+
[county, levenshtein_distance(county.downcase, normalized_string)]
3736
end
3837
counties_with_distances_hash = Hash[*counties_with_distances.flatten]
3938
counties_with_distances_hash.min_by { |_k, v| v }[0]

0 commit comments

Comments
 (0)