Algorithms · real, tested code

Compute the Edit Distance Between Two Strings in Larzscript

The Levenshtein distance: the minimum number of single-character insertions, deletions and substitutions to turn one string into another.

A classic two-row dynamic-programming table - only the previous and current row are ever needed at once, so this stays O(min(n, m)) in space instead of O(n * m).

Code

fn zeros(n) {
  let out = []
  let i = 0
  while i <= n { out.push(i); i = i + 1 }
  return out
}

fn edit_distance(a, b) {
  let n = len(a)
  let m = len(b)
  let prev = zeros(m)
  let curr = zeros(m)
  let i = 1
  while i <= n {
    curr[0] = i
    let j = 1
    while j <= m {
      let cost = a[i-1:i] == b[j-1:j] ? 0 : 1
      let del = prev[j] + 1
      let ins = curr[j-1] + 1
      let sub = prev[j-1] + cost
      let best = del < ins ? del : ins
      if sub < best { best = sub }
      curr[j] = best
      j = j + 1
    }
    let tmp = prev
    prev = curr
    curr = tmp
    i = i + 1
  }
  return prev[m]
}

print(edit_distance("kitten", "sitting"))
print(edit_distance("larzscript", "larzscript"))
print(edit_distance("flaw", "lawn"))
Output
3
0
2