]> git.sommitrealweird.co.uk Git - advent-of-code-2021.git/blob - day14/poly.sh
Working day16 parser
[advent-of-code-2021.git] / day14 / poly.sh
1 #!/bin/bash
2
3 set -u
4
5 filename="${1:-example.txt}"
6 exec 3<"$filename"
7
8 read -u 3 template
9
10 read -u 3 blank
11
12 declare -A inserts=()
13
14 declare -a results=($template)
15
16 while read -u 3 poly; do
17     left="${poly% -> *}"
18     right="${poly#* -> }"
19     inserts[$left]="$right"
20 done
21
22 for (( a=1; a<=10; a++ )); do
23     cur_string="${results[$(($a-1))]}"
24     for (( b=0; b<$((${#cur_string} - 1)); b++ )); do
25         lookup="${cur_string:$b:2}"
26         if [ $b -eq 0 ]; then
27             results[$a]="${lookup:0:1}${inserts[$lookup]}"
28         else
29             results[$a]+="${lookup:0:1}${inserts[$lookup]}"
30         fi
31     done
32     results[$a]+="${cur_string: -1:1}"
33 done
34
35 declare -A counts
36
37 do_counts() {
38     local string="$1"
39     counts=()
40
41     for (( a=0; a<${#string}; a++ )); do
42         char=${string:$a:1}
43         if [ "${counts[$char]+abc}" ]; then
44             ((counts[$char]+=1))
45         else
46             counts[$char]=1
47         fi
48     done
49 }
50
51 get_highest_lowest() {
52     local -n __results="$1"
53     lowest_count=-1
54     lowest_letter=""
55     highest_count=-1
56     highest_letter=""
57     for key in "${!counts[@]}"; do
58         if [ $lowest_count -eq -1 ]; then
59             lowest_count=${counts[$key]}
60             lowest_letter=$key
61         elif [ ${counts[$key]} -lt $lowest_count ]; then
62             lowest_count=${counts[$key]}
63             lowest_letter=$key
64         fi
65         if [ $highest_count -eq -1 ]; then
66             highest_count=${counts[$key]}
67             highest_letter=$key
68         elif [ ${counts[$key]} -gt $highest_count ]; then
69             highest_count=${counts[$key]}
70             highest_letter=$key
71         fi
72     done
73
74     __results[$lowest_count]=$lowest_letter
75     __results[$highest_count]=$highest_letter
76 }
77
78 do_counts "${results[-1]}"
79 declare -a result_counts=()
80 get_highest_lowest result_counts
81
82 declare -a temp=( "${!result_counts[@]}" )
83 echo -n "Part 1: Difference between highest and lowest count: "
84 echo $(("${temp[1]}" - "${temp[0]}"))