aoc/2023/1/2/solution.sh

33 lines
953 B
Bash
Raw Normal View History

2023-12-01 17:11:47 +01:00
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
2023-12-09 16:01:06 +01:00
INPUT=$1
2023-12-01 17:11:47 +01:00
main ()
{
2023-12-01 17:49:17 +01:00
digit_regex="[[:digit:]]|one|two|three|four|five|six|seven|eight|nine"
digit_regex_reverse="[[:digit:]]|eno|owt|eerht|ruof|evif|xis|neves|thgie|enin"
2023-12-01 17:11:47 +01:00
declare -A digits=([one]=1 [two]=2 [three]=3 [four]=4 [five]=5 [six]=6 [seven]=7 [eight]=8 [nine]=9)
declare -a components
declare -i result=0
while read -r line; do
2023-12-01 17:49:17 +01:00
first=$(grep -E -o "${digit_regex}" <<< "${line}" | head -n 1)
last=$(rev <<< "${line}" | grep -E -o "${digit_regex_reverse}" | rev | head -n 1)
2023-12-01 17:11:47 +01:00
first=$([[ ! ${first} =~ ^[0-9]$ ]] && echo "${digits[${first}]}" || echo "${first}")
last=$([[ ! ${last} =~ ^[0-9]$ ]] && echo "${digits[${last}]}" || echo "${last}")
components+=("${first}${last}")
2023-12-09 16:01:06 +01:00
done < "${INPUT}"
2023-12-01 17:11:47 +01:00
for value in "${components[@]}"; do
(( result += value ))
done
echo "${result}"
}
main