Skip to content

Instantly share code, notes, and snippets.

@yveszoundi
Created October 27, 2014 22:19
Show Gist options
  • Save yveszoundi/3180bc721afb260c8bc4 to your computer and use it in GitHub Desktop.
Save yveszoundi/3180bc721afb260c8bc4 to your computer and use it in GitHub Desktop.
Levenshtein distance with only previous row tracking.
(defn levenshtein-distance [w1 w2]
"Computes the levenshtein distance between two words."
(letfn [(cell-value [ch1 ch2 prev-row acc col-idx]
(min (inc (nth prev-row col-idx))
(inc (last acc))
(+ (nth prev-row (dec col-idx)) (if (= ch1 ch2) 0 1))))]
(loop [row-idx 1, max-rows (inc (count w2)), prev (range (inc (count w1)))]
(if (= row-idx max-rows)
(last prev)
(let [ch2 (nth w2 (dec row-idx))
next-prev (reduce (fn [acc i]
(conj acc (cell-value (nth w1 (dec i)) ch2 prev acc i)))
[row-idx]
(range 1 (count prev)))]
(recur (inc row-idx) max-rows, next-prev))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment