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

#
# See ../README.md
#

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

{
    #
    # Read the input, turn in into a graph:
    #  The first and last characters of the strings are the nodes.
    #  There is a directed edge in the graph from the first to the
    #  last character of a string.
    #
    delete graph
    delete nodes
    for (i = 1; i <= NF; i ++) {
        first = substr ($i, 1, 1)
        last  = substr ($i, length ($i))
        graph [first, last] = 1
        nodes [first]       = 1
        nodes [last]        = 1
    }

    #
    # Calculate the transitive closure using the Floyd-Warshall algorithm.
    #
    for (k in nodes) {
        for (i in nodes) {
            for (j in nodes) {
                if (graph [k, j] > 0 && graph [i, k] > 0) {
                    graph [i, j] = 1
                }
            }
        }
    }

    #
    # There's a loop iff there is a node which is reachable from itself.
    #
    out = 0
    for (i in nodes) {
        if (graph [i, i] > 0) {
            out = 1
        }
    }

    print (out)
}