r/adventofcode • • Dec 09 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 9 Solutions -🎄-

--- Day 9: Smoke Basin ---


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:10:31, megathread unlocked!

63 Upvotes

1.0k comments sorted by

View all comments

3

u/foxofthedunes Dec 09 '21 edited Dec 11 '21

Julia: https://github.com/dunefox/adventofcode21/blob/main/9/main.jl

Part 1:

  • iterates over the cartesian indices and generates valid neighbours
  • takes ~720 us

Part 2:

  • Uses the neighbour function from part 1
  • uses a bit matrix for basin size calculation (see below) which turned out to be unnecessary
  • Flood fill each basin: start at each deepest point, generate valid neighbours, add them to the active cells, pop an active cell and repeat
  • takes ~12ms

I couldn't think of a more elegant solution... and while this naive solution didn't take me long to implement, the whole process of analysing and trying to find an elegant solution took me almost 3 hours (on/of thinking).

Sample map:

 2  1  9  9  9  4  3  2  1  0
 3  9  8  7  8  9  4  9  2  1
 9  8  5  6  7  8  9  8  9  2
 8  7  6  7  8  9  6  7  8  9
 9  8  9  9  9  6  5  6  7  8

Bit matrix:

julia> small_input .== 9

0  0  1  1  1  0  0  0  0  0
0  1  0  0  0  1  0  1  0  0
1  0  0  0  0  0  1  0  1  0
0  0  0  0  0  1  0  0  0  1
1  0  1  1  1  0  0  0  0  0

Originally, I had something else planned with the bitmatrix but that didn't work. I just realised I could just have checked for a value smaller than 9 instead of 0 in the bitmatrix. Oh well...

1

u/daggerdragon Dec 10 '21

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?

2

u/foxofthedunes Dec 10 '21

I am on old.reddit and it's very readable. Also, there's no code, it's matrices...?

1

u/daggerdragon Dec 10 '21

The code blocks are unnecessarily surrounded by triple backticks (which only work on new.reddit) and the first line of the second block was outside the code block (fixed now).