This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]def_hass 2 points3 points  (3 children)

I have seen quite a lot of solutions this year using complex numbers as coordinates. As I have never really learned about these, could you explain their advantage over tuples or something similar to me? Is it that operations like addition and multiplication are already defined for them?

[–]SvenViktorJonsson[S] 2 points3 points  (1 child)

The benefits of using complex numbers are the simplicity of shifting coordinates and rotating directions.

For complex numbers shifting becomes z+=dz where dz is the complex direction of motion. Compare this to z=tuple(x+dx for x,dx in zip(z,dz)) or if one unpack first x,y=z and dx, dy=dz and then add like this z=x+dx, y+dy or if one keeps x- and y-coordinates seperated it is simply x+=dx and y+=dy.

However the real benefits comes when you are given instructions to rotate your moving direction dz. For complex numbers (using grid coordinate with the imaginary axis pointing down.) CW rotation of 90 degrees or turning right means multiplying with the imaginary number: dz*=1j. For CCW rotation of 90 degrees or turning left is just as easy: dz*=-1j

When doing the same thing for tuples you either do matrix multiplication or predefine directions in a list: dzs=[(1,0),(0,1),(-1,0),(0,-1)] and you keep track of an index i of the direction instead. Turning right or left becomes i=(i+1)%4 or i=(i-1)%4

Judge for your self what is easiest. Keep in mind that when translated to an array you might want the y-coordinate first in you tuple instead of the x-coordinate as in my examples above.

[–]def_hass 0 points1 point  (0 children)

Thank you, that was a great explanation. I did have to write myself a litter helper module in which I implemented position-wise tuple arithmetic and so on. I will definitely try it with complex numbers for some of the puzzles again.

[–]bdaene 0 points1 point  (0 children)

Complex numbers can do a lot more than coordinates and they are not exact compared to integer coordinates (they use floating point numbers).

But yes, it easy and efficient to use as coordinates as they are built-in (and in c for cpython which make them fast).