Add examples, setup a parser... next bit is going to be tricky and require thought
[advent-of-code-2019.git] / day14 / calc_fuel.sh
1 #!/bin/bash
2
3 basedir=$(dirname $(readlink -f ${BASH_SOURCE}))
4 filename="${1:-31_ORE_1_FUEL.txt}"
5
6 declare -A chemicals
7 declare -A requires
8
9 parse_line() {
10     local line="$1"
11     local p=${line#* => }
12     local r=${line% =>*}
13     local p_count
14     local part
15     local count
16     local chem
17     local -A dict
18     local string
19
20     p_count=${p% *}
21     p=${p#* }
22     r=${r//, /|}
23
24     while [ ${#r} -gt 0 ]; do
25         part=${r%%|*}
26         count=${part% *}
27         chem=${part#* }
28         r=${r#$part}
29         r=${r#|}
30
31         string+=" [$chem]=$count "
32     done
33     requires[${p}_${count}]="$string"
34     if [ ${chemicals[$p]} ]; then
35         chemicals[$p]+=" $count"
36     else
37         chemicals[$p]="$p_count"
38     fi
39 }
40
41 read_file() {
42     exec 3<"$filename"
43     local IFS=$'\n'
44     while read -u 3 line; do
45         parse_line "$line"
46     done
47 }
48
49 read_file
50
51 for key in ${!requires[@]}; do
52     echo "$key -> ${requires[$key]}"
53 done
54
55 echo
56
57 for key in ${!chemicals[@]}; do
58     echo "$key -> ${chemicals[$key]}"
59 done
60
61 declare -A needed
62 needed=( "${requires[FUEL_1]}" )
63
64 for key in ${!needed[@]}; do
65     echo "$key ${needed[$key]}"
66 done