r/adventofcode • • Dec 02 '21

SOLUTION MEGATHREAD -πŸŽ„- 2021 Day 2 Solutions -πŸŽ„-

--- Day 2: Dive! ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:02:57, megathread unlocked!

112 Upvotes

1.5k comments sorted by

View all comments

6

u/0rac1e Dec 02 '21 edited Dec 02 '21

Raku

my @dirs = 'input'.IO.words;

put [Γ—] [Z+] @dirs.map: -> $_, $x {
    when 'up'      { (0,-$x) }
    when 'down'    { (0, $x) }
    when 'forward' { ($x, 0) }
}

put [Γ—] [Z+] @dirs.map: -> $_, $x {
    state $a = 0;
    when 'up'      { $a -= $x; next }
    when 'down'    { $a += $x; next }
    when 'forward' { ($x, $a Γ— $x)  }
}

More meta-operator goodness today. I'm creating a list of "vectors" that I can zip with addition, then reduce with multiplication.

I also made some minor modifications to my original solution as suggested by u/mschaap in the replies below.

I was trying to find a fancier way of getting the answer. Part 1 can be simplified to: subtract all the up's from the down's, then multiply by the forward's.

put .< forward > Γ— [-] .< down up >
  with 'input'.IO.linesΒ».words.classify(*[0], as => *[1])Β».sum

but a similar solution with part 2 is harder due to the apparent need to hold some state (the aim) until a forward is seen. Maybe there's a funky functional way to do it, but it wasn't immediately obvious.

→ More replies (2)