Created
October 6, 2023 17:57
-
-
Save lucaswinningham/fa885168c76e6e57bd6489c25c968f87 to your computer and use it in GitHub Desktop.
Levenshtein
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
module Levenshtein | |
class << self | |
def call(a, b) | |
return cache["#{a}-#{b}"] if cache["#{a}-#{b}"] | |
cache["#{a}-#{b}"] = cache["#{b}-#{a}"] = -> { | |
return a.length if b.length.zero? | |
return b.length if a.length.zero? | |
a_head, a_tail = a.chars.then { |head, *tail| [head, tail.join] } | |
b_head, b_tail = b.chars.then { |head, *tail| [head, tail.join] } | |
return call(a_tail, b_tail) if a_head == b_head | |
[ | |
call(a_tail, b), | |
call(a, b_tail), | |
call(a_tail, b_tail), | |
].min + 1 | |
}.call | |
end | |
private | |
def cache | |
@cache ||= {} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment