~/
Posts
/
Advent of Code RegEx Style

Advent of Code RegEx Style

Below follow a few solutions from the 2023 Advent of Code challenges, day 1-4. These are one line solutions comprised mostly of regular expressions with a few command line utilities to achieve the correct answers.

Solutions

— Day 1: Trebuchet?! — Using input.txt

echo "$(cat input.txt | sed -E 's/[a-zA-Z]*//g;s/^(.)[0-9]*([0-9]$)/\1\2/;s/^([0-9])$/\1\1/' | tr '\n' '+')"0 | bc

— Day 1: Part Two — Using same input as above

echo "$(cat input.txt | sed -E 's/twone/21/g;s/oneight/18/g;s/eightwo/82/g;s/one/1/g;s/two/2/g;s/three/3/g;s/four/4/g;s/five/5/g;s/six/6/g;s/seven/7/g;s/eight/8/g;s/nine/9/g;s/zero/0/g;' |sed -E 's/[a-zA-Z]*//g;s/^(.)[0-9]*([0-9]$)/\1\2/;s/^([0-9])$/\1\1/' | tr '\n' '+')"0 | bc

— Day 2: Cube Conundrum — Using input.txt

echo $(grep -v -e "1[3-9][0-9]* red" -e "1[4-9][0-9]* green" -e "1[5-9][0-9]* blue" input.txt | awk '{ print $2 }' | tr ":" "+" | tr -d "\n")0 | bc

— Day 2: Part Two — Using same input as above

cat input.txt | echo "$(while read line; do echo $line | sed -E 's/Game [0-9][0-9]?\://' | tr ";" "," | tr "," "\n" | sort -hr | gawk '{line=line " " $0} END {print line}' | sed -E 's/([0-9][0-9]? green)/\@\1/;s/([0-9][0-9]? blue)/\@\1/;s/([0-9][0-9]? red)/\@\1/;s/^/€/;s/$/€/' | grep -o -E "@[0-9][0-9]?|€" | tr "\n" " " | tr "€" "\n" | sed -E 's/@//;s/ //g;s/@/\*/g' | bc ; done)" | tr "\n" "+" | sed -E 's/\+$/\n/' | bc

— Day 3: Gear Ratios — Using input.txt

echo "$(cat <(printf ".%.0s" {1..141}) <(sed s/$/./ input.txt) <(printf ".%.0s" {1..141}) | tr -d "\n"|  perl -pe "1 while s/(\.){5}.{136}\.\K[0-9][0-9][0-9](?=\..{136}(\.){5})/xxx/g;s/(\.){4}.{137}\.\K[0-9][0-9](?=\..{137}(\.){4})/xx/g;s/\.\.\..{138}\.\K[0-9](?=\..{138}\.\.\.)/x/g" |  perl -pe "1 while s/(\.){5}.{136}\.\K[0-9][0-9][0-9](?=\..{136}(\.){5})/xxx/g;s/(\.){4}.{137}\.\K[0-9][0-9](?=\..{137}(\.){4})/xx/g;s/\.\.\..{138}\.\K[0-9](?=\..{138}\.\.\.)/x/g" | sed -E 's/[^0-9]+/+/g;s/^\+//;s/\+$//')" | bc

— Day 4: Scratchcards — Using input.txt

echo -e "$(cat input.txt | sed -E 's/^.*\://;s/$/ /' | perl -pe 's/((?=(\s\d{1,2}\s).*(\2)))/ M/g;s/M\s([0-9])/M\1/g;s/\|.*$//;s/ \d+//g;s/[ ]+/ /g' | awk '{ print gsub(/M/, "&") }' | grep -v "^0$" | sed -E 's/^(.*)$/\(1\*2\^\(\1-1\)\)/' | tr "\n" "+" | sed 's/+$//')" | bc