3 ms·
I did a fun thing with Sympy for Advent of Code 2017 December 3rd, here's a Jupyter notebook if anyone's interested: https://osdn.net/projects/joypy/scm/hg/Joyp
by carapace 6y ago
I did a fun thing with Sympy for Advent of Code 2017 December 3rd, here's a Jupyter notebook if anyone's interested: https://osdn.net/projects/joypy/scm/hg/Joypy/blobs/tip/docs/Advent_of_Code_2017_December_3rd.ipynb https://osdn.net/projects/joypy/scm/hg/Joypy/blobs/tip/docs/...
The puzzle involves a weird "spiral" RAM:
> You come across an experimental new kind of memory stored on an
infinite two-dimensional grid.
> Each square on the grid is allocated in a spiral pattern starting at a
location marked 1 and then counting up while spiraling outward.
The problem is to compute "the Manhattan Distance between the location of
the data and square 1" for any given square.
While working on this I came up with the following equation:
from sympy import floor, lambdify, solve, symbols
k = symbols('k')
E = 2 + 8 * k * (k + 1) / 2
Sympy figures out that this reduces to E = 4k(k + 1) + 2
I needed a function to solve for k given some n... Sympy can do that. Take a new symbol `n`, subtract it from the equation `E`, 0 = 4k(k + 1) + 2 - n and solve for `k`. There are two solutions because the equation is quadratic so it has two roots.
n = symbols('n')
g, f = solve(E - n, k)
In the context of the puzzle we only care about the larger root:
(sqrt(n - 1) / 2 - 0.5) + 1
For reasons, I need to take the floor and add 1. Then Sympy can lambdify it and create a fast Python function to compute `k`, given `n`:
F = lambdify(n, floor(f) + 1)
for n in (9, 10, 25, 26, 49, 50):
print(n, int(F(n)))
9 1
10 2
25 2
26 3
49 3
50 4
I'm sorry that it's hard to follow, I'm just excited to share how cool it
was to let the computer do the symbolic math for me.