Complex Numbers and the Mars Rover Challenge

Here is how to solve the Mars Rover Challenge using complex numbers.

In the calculations below, j is √(-1).

Complex multiplication represents rotation, and complex addition represents translation.

Mapping of headings:

North j
East 1
West -1
South -j

Mapping of the rover commands:

L Rotate left by 90 degrees Multiply the heading by j
R Rotate right by 90 degrees Multiply the heading by -j
M Move forward Add the heading to the position
Example 1:

A rover is facing North and we issue an R (rotate right) command. We expect it to face East. We multiply the heading by -j, which corresponds to the R command.

        North * R
        = j * -j
        = 1
        = East // position unchanged
      
Example 2:

A rover is at (1,2) facing East and we issue an M (move forward) command. We expect it to be at (2,2). We add the heading East to the position.

        rover position (1,2) + East
        = (1 + 2j) + 1
        = 2 + 2j
        = (2, 2) // orientation unchanged
    

In the golang implementation, position and orientation are represented as complex numbers using a custom vect type. The built-in complex type is not used because it relies on floats, which can’t be compared easily.