From 0f431e9e3f51304b729bf329996fb1e9bdf66a5c Mon Sep 17 00:00:00 2001 From: Akshay Mankar Date: Sat, 2 Dec 2023 10:12:35 +0100 Subject: [PATCH] [bash] Solve Day 2 --- bash/day2.sh | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100755 bash/day2.sh diff --git a/bash/day2.sh b/bash/day2.sh new file mode 100755 index 0000000..bbd48de --- /dev/null +++ b/bash/day2.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash + +set -euo pipefail + +sumNumbers() { + local sum + sum=0 + while IFS= read -r num || [[ -n "$num" ]]; do + sum=$(( "$sum" + "$num" )) + done + echo "$sum" +} + +gameIds () { + sed 's|Game \(.*\): .*|\1|' +} + +maxColour() { + local colour counts + colour=$1 + counts=$(echo "0 $colour" + sed 's|Game .*: ||; + s|, |\n|g; + s|; |\n|g' | + grep "$colour") + sort --general-numeric-sort <<< "$counts" | + tail -1 | + sed "s| $colour||" +} + +gamesWhichFitTheLimit() { + local maxReds maxGreens maxBlues + while IFS= read -r line || [[ -n "$line" ]]; do + maxReds=$(maxColour "red" <<< "$line") + maxGreens=$(maxColour "green" <<< "$line") + maxBlues=$(maxColour "blue" <<< "$line") + if [[ "$maxReds" -le 12 ]] && [[ "$maxGreens" -le 13 ]] && [[ "$maxBlues" -le 14 ]]; then + echo "$line" + fi + done +} + +powers () { + local maxReds maxGreens maxBlues + while IFS= read -r line || [[ -n "$line" ]]; do + maxReds=$(maxColour "red" <<< "$line") + maxGreens=$(maxColour "green" <<< "$line") + maxBlues=$(maxColour "blue" <<< "$line") + echo "$(( "$maxReds" * "$maxGreens" * "$maxBlues"))" + done +} + +main () { + local input + input=$(cat) + echo "Part 1 Answer: $(<<<"$input" gamesWhichFitTheLimit | gameIds | sumNumbers)" + echo "Part 2 Answer: $(<<<"$input" powers | sumNumbers)" +} + +main