9
votes
Day 9: Rope Bridge
Today's problem description: https://adventofcode.com/2022/day/9
Please post your solutions in your own top-level comment. Here's a template you can copy-paste into your comment to format it nicely, with the code collapsed by default inside an expandable section with syntax highlighting (you can replace python
with any of the "short names" listed in this page of supported languages):
<details>
<summary>Part 1</summary>
```python
Your code here.
```
</details>
My Python solution, using complex numbers (which are helpfully one of the language's basic numeric types). Another great problem from Eric!
Part 1
Part 2
Wait... what?
Complex numbers have both real and imaginary parts, so they can treated as Cartesian co-ordinates, x being the real and y the imaginary.
e.g. In python if your point P is
1+2j
Cardinal directions can also be complex numbers:
N:
0+1j
S:0-1j
E: 1+0j
W: -1+0j
You can move just by addition
P+N = 1+3j
P+S = 1+1j
P+W = 0+2j
- displayed just as2j
P+E = 2+2j
You can also change direction by turning left, L=N:
0+1j
or right, R=S:0-1j
using multiplication.I'm doing this from memory so I might have got the exact details wrong, but the idea is correct.
Part 1, in Python-ish
Python code generated from the above
Part 2, in Python-ish
Python code generated from the above
Elixir
I tried to "speedrun" this one but tripped myself up for a while on part 1 by referencing the previous value of the head when determining whether the tail was adjacent to it!
Overall my code is pretty messy, but I'm happy with how easy it was to adapt it to part 2. I'll probably come back later and clean it up.
Both parts
Part 1 runs in about 7 ms, part 2 in about 15 ms.
Shortened with excessive weird one-line functions!! Also, I realized that
Enum.scan/2
was perfect for propagating movements down the length of the rope.Both parts but shorter
Python
Today reminded me of this
Utilities
Part 1
Part 2
Converted
cross-river
from using just head and tail of the rope to a hash of knots.It makes part 2 very simple.
Well my attempts at shortcuts certainly didn't do me any favors in part 2.
Part 1
The idea was basically to move to the previous position of the head if there are more than two spaces between them.Part 2
I had to rewrite the logic for this part due to the more complex movements possible.Late, long, and clunky, but correct solution! Ended up refactoring for part 2 to make things configurable which helped marginally, but not as much as one might hope, since that wasn't really the part I'm not proud of anyway lol.
Part 1 and 2, Python