Day 1 Part 2
This commit is contained in:
commit
b0877a7d95
1000
1/2/input.txt
Normal file
1000
1/2/input.txt
Normal file
File diff suppressed because it is too large
Load Diff
21
1/2/puzzle.txt
Normal file
21
1/2/puzzle.txt
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
--- Part Two ---
|
||||||
|
|
||||||
|
Your calculation isn't quite right. It looks like some of the
|
||||||
|
digits are actually spelled out with letters: one, two, three, four, five, six,
|
||||||
|
seven, eight, and nine also count as valid "digits".
|
||||||
|
|
||||||
|
Equipped with this new information, you now need to find the real first and last
|
||||||
|
digit on each line. For example:
|
||||||
|
|
||||||
|
two1nine
|
||||||
|
eightwothree
|
||||||
|
abcone2threexyz
|
||||||
|
xtwone3four
|
||||||
|
4nineeightseven2
|
||||||
|
zoneight234
|
||||||
|
7pqrstsixteen
|
||||||
|
|
||||||
|
In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76.
|
||||||
|
Adding these together produces 281.
|
||||||
|
|
||||||
|
What is the sum of all of the calibration values?
|
32
1/2/solution.sh
Executable file
32
1/2/solution.sh
Executable file
@ -0,0 +1,32 @@
|
|||||||
|
#!/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")"
|
||||||
|
|
||||||
|
main ()
|
||||||
|
{
|
||||||
|
numbers="[[:digit:]]|one|two|three|four|five|six|seven|eight|nine"
|
||||||
|
numbers_reverse="[[:digit:]]|eno|owt|eerht|ruof|evif|xis|neves|thgie|enin"
|
||||||
|
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
|
||||||
|
first=$(grep -E -o "${numbers}" <<< "${line}" | head -n 1)
|
||||||
|
last=$(rev <<< "${line}" | grep -E -o "${numbers_reverse}" | rev | head -n 1)
|
||||||
|
first=$([[ ! ${first} =~ ^[0-9]$ ]] && echo "${digits[${first}]}" || echo "${first}")
|
||||||
|
last=$([[ ! ${last} =~ ^[0-9]$ ]] && echo "${digits[${last}]}" || echo "${last}")
|
||||||
|
components+=("${first}${last}")
|
||||||
|
done < input.txt
|
||||||
|
for value in "${components[@]}"; do
|
||||||
|
(( result += value ))
|
||||||
|
done
|
||||||
|
echo "${result}"
|
||||||
|
}
|
||||||
|
|
||||||
|
main
|
Loading…
Reference in New Issue
Block a user