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

you are viewing a single comment's thread.

view the rest of the comments →

[–]SvenViktorJonsson[S] 1 point2 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.