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
Related
FizzBuzz in LarzscriptThe classic interview warm-up: print 1 to N, but Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both.→Reverse a String in LarzscriptFlip a string end to end - one of the smallest real string algorithms, and a good first look at the str package.→Check if a String is a Palindrome in LarzscriptDetect whether a string reads the same forwards and backwards, ignoring case, spaces and punctuation.→Sort a List in LarzscriptSort a list of numbers - and see exactly how many comparisons and swaps each algorithm actually costs.→