4 ms·
In a past codegolf contest you had to parse some input consisting of L, S, R for left, straight, right to follow a path. I used complex numbers and the fact th
by orlp 4y ago
In a past codegolf contest you had to parse some input consisting of L, S, R for left, straight, right to follow a path.
I used complex numbers and the fact that L, S, R respectively have ASCII codes 82, 83, 76 in the identities
i^(82 + 1) = -i
i^(83 + 1) = 1
i^(76 + 1) = i
to get a very compact path reconstruction.
- tomstuart 4y agoThis is incredibly clever. In case anyone else is confused by the order: the ASCII codes for L, S, R are 76, 83, 82 respectively, so L encodes i and R encodes -i as you’d expect.
- zasdffaa 4y agoWhat?? Could you go a little deeper into the complex numbers thing, it sounds so nutty.
- tomstuart 4y agoA complex number represents a 2D point in the complex plane, but multiplication by a complex number on the unit circle also happens to correspond to a rotation in the complex plane, e.g. 3 × i = 3i, which is a rotation of 90 degrees anticlockwise, or -5i × -i = -5, which is a rotation of 90 degrees clockwise. So if you use the complex numbers 1, i and -i to represent the actions “go straight”, “turn left” and “turn right” respectively, you can update a complex number representing the current heading of the snake (1 = east, i = north, -1 = west, -i = south) by multiplying it by the action. To get the snake’s current position, add up all the “current heading” numbers you’ve seen so far.