Add examples, setup a parser... next bit is going to be tricky and require thought
[advent-of-code-2019.git] / day14 / calc_fuel.sh
diff --git a/day14/calc_fuel.sh b/day14/calc_fuel.sh
new file mode 100644 (file)
index 0000000..d32e397
--- /dev/null
@@ -0,0 +1,66 @@
+#!/bin/bash
+
+basedir=$(dirname $(readlink -f ${BASH_SOURCE}))
+filename="${1:-31_ORE_1_FUEL.txt}"
+
+declare -A chemicals
+declare -A requires
+
+parse_line() {
+    local line="$1"
+    local p=${line#* => }
+    local r=${line% =>*}
+    local p_count
+    local part
+    local count
+    local chem
+    local -A dict
+    local string
+
+    p_count=${p% *}
+    p=${p#* }
+    r=${r//, /|}
+
+    while [ ${#r} -gt 0 ]; do
+        part=${r%%|*}
+        count=${part% *}
+        chem=${part#* }
+        r=${r#$part}
+        r=${r#|}
+
+        string+=" [$chem]=$count "
+    done
+    requires[${p}_${count}]="$string"
+    if [ ${chemicals[$p]} ]; then
+        chemicals[$p]+=" $count"
+    else
+        chemicals[$p]="$p_count"
+    fi
+}
+
+read_file() {
+    exec 3<"$filename"
+    local IFS=$'\n'
+    while read -u 3 line; do
+        parse_line "$line"
+    done
+}
+
+read_file
+
+for key in ${!requires[@]}; do
+    echo "$key -> ${requires[$key]}"
+done
+
+echo
+
+for key in ${!chemicals[@]}; do
+    echo "$key -> ${chemicals[$key]}"
+done
+
+declare -A needed
+needed=( "${requires[FUEL_1]}" )
+
+for key in ${!needed[@]}; do
+    echo "$key ${needed[$key]}"
+done