diff --git a/bash/day1.sh b/bash/day1.sh new file mode 100755 index 0000000..acaa8a9 --- /dev/null +++ b/bash/day1.sh @@ -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 diff --git a/bash/main.sh b/bash/main.sh new file mode 100755 index 0000000..7fcf9de --- /dev/null +++ b/bash/main.sh @@ -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