aboutsummaryrefslogtreecommitdiff
path: root/challenge-115/abigail/awk/ch-2.awk
blob: 2b2162d5f0553d6aebbc8bdecec44593d897e9ba (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
#!/usr/bin/awk

#
# See ../README.md
#

#
# Run as: awk -f ch-2.awk < input-file
#

{
    #
    # Initialize digits array
    #
    for (i = 0; i < 10; i ++) {
        digits [i] = 0
    }

    #
    # Read in the data; count digits
    #
    for (i = 1; i <= NF; i ++) {
        digits [$i] ++
    }

    #
    # Find the smallest even number; this one goes last
    #
    last = -1
    for (i = 0; i < 10 && last < 0; i += 2) {
        if (digits [i] > 0) {
            last = i
            digits [i] --
        }
    }

    #
    # Skip if the input does not contain an even digit
    #
    if (last < 0) {
        next
    }

    #
    # Create the output: rest of digits are from highest to lowest
    #
    out = ""
    for (i = 9; i >= 0; i --) {
        while (digits [i] -- > 0) {
            out = out i
        }
    }
    print out last
}