aboutsummaryrefslogtreecommitdiff
path: root/challenge-115/abigail/bash/ch-1.sh
blob: 06cab4514f77d1b2fcd057426c2ef7ea1d90dae2 (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
#!/bin/sh

#
# See ../README.md
#

#
# Run as: bash ch-1.sh < input-file
#

set -f
declare -A nodes
declare -A graph

while read -a strings
do    nodes=()
      graph=()
      #
      # Read in the strings. Build a graph where the first and last
      # characters of the strings are the nodes, and for each string
      # we have a directed edge from the first character to its last.
      #
      for   string in ${strings[@]}
      do    first=${string:0:1}
            last=${string:$((${#string}-1)):1}
            nodes[$first]=1
            nodes[$last]=1
            graph[$first$last]=1
      done

      #
      # Calculate the transitive closure using the Floyd-Warshall algorithm.
      #
      for   k in ${!nodes[@]}
      do    for i in ${!nodes[@]}
            do    for   j in ${!nodes[@]}
                  do    if [ X${graph[$k$j]} == X1 -a \
                             X${graph[$i$k]} == X1 ]
                        then graph[$i$j]=1
                        fi
                  done
            done
      done

      #
      # There's a cycle iff there's a node which is reachable from itself.
      #
      out=0
      for   i in ${!nodes[@]}
      do    if   [ X${graph[$i$i]} == X1 ]
            then out=1
            fi
      done

      echo $out
done