英文:
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?
英文:
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?
答案1
得分: 4
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 ![]()
英文:
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!)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论