To paraphrase the puzzle, Santa takes a walk with an Elf, and they play a game involving a bag of colorful cubes. In each game, there is an unknown number of each colored cubes in the bag, and the Elf pulls out a number of cubes, for example:
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
Part 1
In part 1, we want to know which games would have been possible if the bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes. The answer is the sum of the eligible game ids, in the above example 1 + 2 + 5 = 8.
#!/usr/bin/env bash
#
# Solver for https://adventofcode.com/2023/day/2 part 1
# Redirect the input file to this script, for example day2part1.sh < path/to/input.txt
#
set -euo pipefail
max_red=12
max_green=13
max_blue=14
is_eligible_cubes() {
local count color
count=$1
color=$2
case $color in
red) ((max_red < count)) && return 1 ;;
green) ((max_green < count)) && return 1 ;;
blue) ((max_blue < count)) && return 1 ;;
esac
return 0
}
is_eligible_game() {
local iterations count color
iterations=$1
while [ "$iterations" ]; do
[[ $iterations =~ ([0-9]+)\ (red|green|blue) ]] || break
count=${BASH_REMATCH[1]}
color=${BASH_REMATCH[2]}
iterations=${iterations:${#BASH_REMATCH[0]}}
iterations=${iterations#*[,;]}
is_eligible_cubes "$count" "$color" || return 1
done
return 0
}
solve_day2_part1() {
local sum game_id iterations
sum=0
while read _ game_id iterations; do
game_id=${game_id%:}
is_eligible_game "$iterations" && ((sum += game_id))
done
echo "$sum"
}
solve_day2_part1
Part 2
To paraphrase the change in part 2, for each game, we're looking for the maximum number of cubes per color that were drawn, multiply them together, and then sum this number for all games. With the example above this would be 48 + 12 + 1560 + 630 + 36 = 2286.
#!/usr/bin/env bash
#
# Solver for https://adventofcode.com/2023/day/2 part 2
# Redirect the input file to this script, for example day2part2.sh < path/to/input.txt
#
set -euo pipefail
solve_day2_part2() {
local sum game_id iterations count color red green blue
sum=0
while read _ game_id iterations; do
game_id=${game_id%:}
red=0
green=0
blue=0
while [ "$iterations" ]; do
[[ $iterations =~ ([0-9]+)\ (red|green|blue) ]] || break
count=${BASH_REMATCH[1]}
color=${BASH_REMATCH[2]}
iterations=${iterations:${#BASH_REMATCH[0]}}
iterations=${iterations#*[,;]}
case $color in
red) ((red < count)) && red=$count ;;
green) ((green < count)) && green=$count ;;
blue) ((blue < count)) && blue=$count ;;
esac
done
((sum += red * green * blue))
done
echo "$sum"
}
solve_day2_part2
Review request
What would you do differently?