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

Question:

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?

Asked By: outis

||

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!)

Answered By: Kelly Bundy