Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of using complex numbers to store graph coordinates?

I am looking at a solution to an Advent of Code puzzle that stores coordinates as complex numbers:

 heightmap = {
    complex(x, y): c
        for y, ln in enumerate(sys.stdin.read().strip().split("\n"))
        for x, c in enumerate(ln)
}

Then accesses them later as follows:

for xy, c in heightmap.items():
    for d in (1, -1, 1j, -1j):
        if ord(heightmap.get(xy + d, "{")) <= ord(c) + 1:
            G.add_edge(xy, xy + d)

I can see that this code makes the 'get neighbors' line easy to write/think about, but I don't see that it is worth the added complexity (no pun intended).

Can someone explain why it's useful to store the grid coordinates as complex numbers?

like image 415
outis Avatar asked Oct 21 '25 12:10

outis


1 Answers

Yes, because it's easy/less to write and think about. Also means less opportunity for typos :-)

I've been doing that for years, ever since I saw someone else do that. Usually not even typing the deltas explicitly but calculating them. I.e., instead of

for d in (1, -1, 1j, -1j):
    use(z + d)

do:

for i in range(4):
    use(z + 1j**i)

Possible alternatives when using separate x and y variables:

for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
    use(x+dx, y+dy)
for x2, y2 in ((x+1, y), (x, y+1), (x-1, y), (x, y-1)):
    use(x2, y2)

Ermahgerd, so frustrating. I actually did make several typos while writing these :-)

(Tests at Attempt This Online!)

like image 93
Kelly Bundy Avatar answered Oct 23 '25 02:10

Kelly Bundy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!