## Roomba

### January 19, 2018

The hard part of this exercise is parsing the command string, as the arithmetic of calculating the position after each move is easy. Here’s our parser, which makes natural use of several functions from the Standard Prelude:

(define (get-command cs) (call-with-values (lambda () (split 1 cs)) (lambda (dir rest) (call-with-values (lambda () (split-while char-numeric? rest)) (lambda (digits rest) (values (car dir) (string->number (apply string digits)) rest))))))

We are assuming the command string is properly formed; various errors will result if it isn’t. Then we calculate the position after each move command:

(define (roomba x y str) (let loop ((x x) (y y) (cs (string->list str))) (if (null? cs) (values x y) (call-with-values (lambda () (get-command cs)) (lambda (dir steps rest) (case dir ((#\N #\n) (loop x (+ y steps) rest)) ((#\E #\e) (loop (+ x steps) y rest)) ((#\S #\s) (loop x (- y steps) rest)) ((#\W #\w) (loop (- x steps) y rest))))))))

And that’s it. Here are two examples:

> (roomba 0 0 "N3E5S2W6") -1 1 > (roomba 17 -3 "W4S19W33N17E37N2") 17 -3

You can run the program at https://ideone.com/3P3WAL.

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.