aoc/2023/2/1/solution.sh

43 lines
938 B
Bash
Executable File

#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
INPUT=$1
main ()
{
declare -a colors=(red green blue)
declare -A limits=([red]=12 [green]=13 [blue]=14)
declare -a possible_ids
while read -r game; do
possible=true
stripped_game=$(sed 's/^Game [0-9]\+: //' <<< "${game}")
IFS=';' read -r -a sets <<< "${stripped_game}"
for (( i=0; i<${#sets[@]}; i++ )); do
for color in "${colors[@]}"; do
count=$(grep -o "[0-9]* ${color}" <<< "${sets[$i]}" | grep -o '[0-9]*' || true)
if [[ $count -gt ${limits[$color]} ]]; then
possible=false
break 2
fi
done
done
if $possible; then
id=$(grep -o '[0-9]*' <<< "${game}" | head -n 1)
possible_ids+=($id)
fi
done < "${INPUT}"
declare -i sum=0
for id in "${possible_ids[@]}"; do
(( sum+=id ))
done
echo $sum
}
main