## Roomba

### January 19, 2018

A robot can move any number of steps in the four cardinal directions. Given the robot’s initial position and a string of moves given as, for instance, N3E5S2W6 (any of the four cardinal directions, followed by any number of steps, as many commands as desired), determine the ending position of the robot.

Your task is to write a program to determine the ending position of a robot, given a starting position and a string of move commands. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisements

This is where regex’s become useful…

Here is my take on this problem, using Julia and mapping everything on the Complex number plane:

global CP = [‘N’, ‘S’, ‘E’, ‘W’]

function Cardinal2Numeric(x::AbstractString)

x = uppercase(x)

d = x[1]

end

function Numeric2Cardinal(x::Complex)

y = “”

a = imag(x)

b = real(x)

end

function main(x::AbstractString)

x = uppercase(x)

z = Complex(0, 0)

c = 1

n = length(x)

end

It could be done in a more simpler way, but I’ve never worked with Complex numbers in Julia and I’m always up for a challenge!

In Python.

Here’s a solution in C.

Output:

Here’s a Haskell version. It uses the attoparsec library for parsing a sequence of moves and the linear library for the two-dimensional vectors that represent those moves. Upon parsing, a direction is replaced by a unit vector in the appropriate direction, multiplied by the number of steps. The vectors are then added to form a single vector representing the sequence of moves. That result is added to a starting location to give a final location.