aboutsummaryrefslogtreecommitdiff
path: root/challenge-096/abigail/lua/ch-2.lua
blob: 99058213cadc34030fb397968b0c71f238db6024 (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
67
68
69
70
71
#!/opt/local/bin/lua

--
-- See ../README.md
--

--
-- Run as: lua ch-2.lua < input-file
--

--
-- 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 ()
    distance = {}
    for i = 0, n do
        distance [i] = {}
        for j = 0, m do
            if i == 0 or j == 0
            then
                distance [i] [j] = i + j
            else
                local cost = 1
                if string . sub (first,  i, i) ==
                   string . sub (second, j, j)
                then
                    cost = 0
                end
                distance [i] [j] = math . min (
                    distance [i - 1] [j]     + 1,
                    distance [i]     [j - 1] + 1,
                    distance [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 Theta (n * m) to O (n + m)
        --
        if i > 0
        then
            distance [i - 1] = nil
        end
    end
    return distance [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