[bash] Solve Day 1

This commit is contained in:
Akshay Mankar 2023-12-01 10:56:09 +01:00
parent 35ba38bd13
commit db4b866c76
Signed by: axeman
GPG key ID: CA08F3AB62369B89
2 changed files with 115 additions and 0 deletions

102
bash/day1.sh Executable file
View file

@ -0,0 +1,102 @@
#!/usr/bin/env bash
set -euo pipefail
firstDigits() {
sed 's|^[^0-9]*\([0-9]\).*|\1|'
}
lastDigits() {
sed 's|^.*\([0-9]\)[^0-9]*$|\1|'
}
sumTensDigits() {
echo $(("$(xargs -I '{}' echo '{} * 10 +') 0"))
}
sumOnesDigits() {
echo $(("$(xargs -I '{}' echo '{} +') 0"))
}
detectDigits() {
sed '
s|zero|0|g;
s|twone|2|g;
s|one|1|g;
s|eightwo|8|g;
s|two|2|g;
s|eighthree|8|g;
s|three|3|g;
s|four|4|g;
s|five|5|g;
s|six|6|g;
s|seven|7|g;
s|nineight|9|g;
s|eight|8|g;
s|nine|9|g
'
}
detectReverseDigits() {
sed '
s|enorez|1|g
s|orez|0|g;
s|thgieno|8|g;
s|eno|1|g;
s|owt|2|g;
s|thgieerht|8|g;
s|eerht|3|g;
s|ruof|4|g;
s|thgievif|8|g;
s|evif|5|g;
s|xis|6|g;
s|enineves|9|g
s|neves|7|g;
s|thgie|8|g;
s|enin|9|g
'
}
part1 () {
local input tensSum onesSum
input=$(cat)
tensSum=$(<<< "$input" firstDigits | sumTensDigits)
onesSum=$(<<< "$input" lastDigits | sumOnesDigits)
echo $(("$tensSum + $onesSum"))
}
part2 () {
local input tensSum onesSum
input=$(cat)
tensSum=$(<<< "$input" detectDigits | firstDigits | sumTensDigits)
onesSum=$(<<< "$input" rev | detectReverseDigits | firstDigits | sumOnesDigits)
echo $(("$tensSum + $onesSum"))
}
main () {
local input part1Answer part2Answer
input=$(cat)
part1Answer=$(part1 <<< "$input")
echo "Part 1 Answer: $part1Answer"
part2Answer=$(part2 <<< "$input")
echo "Part 2 Answer: $part2Answer"
}
main

13
bash/main.sh Executable file
View file

@ -0,0 +1,13 @@
#!/usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
case "$1" in
"day1")
"$SCRIPT_DIR/day1.sh"
;;
*)
echo "Invalid day"
exit 1
;;
esac