aboutsummaryrefslogtreecommitdiff
path: root/challenge-115/abigail/lua/ch-2.lua
blob: 4b92535d53760e722f89b449d2b6b72bf1ebf1f8 (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
#!/opt/local/bin/lua

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

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

local NR_OF_DIGITS = 10

for line in io . lines () do

    -- 
    -- Process the input, count digits
    --
    local digits = {}
    for i = 0, NR_OF_DIGITS - 1
    do  digits [i] = 0
    end
    for d in line : gmatch ("%d")
    do  d = tonumber (d)
        digits [d] = digits [d] + 1
    end

    -- 
    -- Find the lowest even digit
    --
    local last = -1
    for i = NR_OF_DIGITS - 2, 0, -2
    do  if   digits [i] > 0
        then last = i
        end
    end

    --
    -- Skip if there is no even digit in the input
    --
    if   last < 0
    then goto end_loop
    end

    digits [last] = digits [last] - 1

    --
    -- Create output: digits from high to low
    --
    local out = ""
    for i = NR_OF_DIGITS - 1, 0, -1
    do  for j = 1, digits [i]
        do  out = out .. tostring (i)
        end
    end

    print (out .. tostring (last))

    ::end_loop::
end