#!/usr/bin/env bash set -o errexit set -o nounset set -o pipefail if [[ "${TRACE-0}" == "1" ]]; then set -o xtrace fi cd "$(dirname "$0")" mapfile -t -O 1 INPUT < "input.txt" CARDS="${#INPUT[@]}" run_cards () { for ((x=1; x<=CARDS; x++)); do declare -a winning=() mine=() declare -i matching=0 declare -i count="${hand[$x]}" stripped=$(sed 's/Card\s\{1,3\}[0-9]\{1,3\}: //' <<< "${INPUT[$x]}") winning+=($(cut -d '|' -f 1 <<< "${stripped}")) mine+=($(cut -d '|' -f 2 <<< "${stripped}")) for number in "${mine[@]}"; do for w in "${winning[@]}"; do if [[ ${number} -eq ${w} ]]; then matching=$((matching+1)) break fi done done for ((i=1; i<=matching; i++)); do hand[$((x+i))]=$((${hand[$((x+i))]}+count)) done done } main () { declare -i sum=0 declare -A hand=() for ((z=1; z<=CARDS; z++)); do hand+=([${z}]=1) done run_cards "${hand[@]}" for ((z=1; z<=CARDS; z++)); do sum=$((sum+${hand[$z]})) done echo "${sum}" } main "$@"