aboutsummaryrefslogtreecommitdiff
path: root/challenge-096/abigail/lua/ch-2.lua
blob: 162f06eef0b15dd6f2221710d9364707befb1826 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
--
-- This is an implementation of the Wagner Fischer algorithm, which
-- calculates the Levenshtein distance.
--
-- See https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm
--
function LevenshteinDistance (first, second)
    local n = first  : len ()
    local m = second : len ()
    if n < m
    then
        first, second = second, first
        n,     m      = m,      n
    end
    distances = {}
    for i = 0, n do
        distances [i] = {}
        for j = 0, m do
            if i == 0 or j == 0
            then
                distances [i] [j] = i + j
            else
                local cost = 1
                if string . sub (first,  i, i) ==
                   string . sub (second, j, j)
                then
                    cost = 0
                end
                distances [i] [j] = math . min (
                    distances [i - 1] [j]     + 1,
                    distances [i]     [j - 1] + 1,
                    distances [i - 1] [j - 1] + cost
                )
            end
        end

        --
        -- We only need the previous row, so we can return the
        -- memory of rows before that. This reduces the memory
        -- usage from O (n * m) to O (min (n, m))
        --
        if i > 0
        then
            distances [i - 1] = nil
        end
    end
    return distances [n] [m]
end


for line in io . lines () do
    --
    -- Extract words and put them into an array.
    --
    local words = {}
    index = 0
    for str in string . gmatch (line, "[^ ]+") do
        index = index + 1
        words [index] = str
    end

    --
    -- Calculate the edit distance, and print the result.
    --
    io . write (LevenshteinDistance (words [1], words [2]), "\n")
end