Skip to content

Instantly share code, notes, and snippets.

@lucaswinningham
Created October 6, 2023 17:57
Show Gist options
  • Save lucaswinningham/fa885168c76e6e57bd6489c25c968f87 to your computer and use it in GitHub Desktop.
Save lucaswinningham/fa885168c76e6e57bd6489c25c968f87 to your computer and use it in GitHub Desktop.
Levenshtein
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