[bash] Solve Day 2

This commit is contained in:
Akshay Mankar 2023-12-02 10:12:35 +01:00
parent 3afccf369f
commit 0f431e9e3f
Signed by: axeman
GPG key ID: CA08F3AB62369B89

60
bash/day2.sh Executable file
View file

@ -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