Created
February 2, 2010 13:20
-
-
Save sadache/292659 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Space.Rovers | |
open System | |
type Direction= N | E | S | W | |
let direction= function 'N' ->N |'E'->E |'S'->S |'W'->W | |
|_-> raise (new ArgumentOutOfRangeException()) | |
let swap (x,y)=(y,x) | |
let rec neighbours = function N -> (W,E) | |
| E -> (N,S) | |
| S -> neighbours N |> swap | |
| W -> neighbours E |> swap | |
type RoverState=Position*Direction | |
and Position= int*int | |
let move state= let ((x,y),direction)=state in | |
match direction with N -> (x,y+1) |E-> (x+1,y) | |
|S -> (x,y-1) |W-> (x-1,y) | |
let execute state= let (position,direction)=state | |
let left,right= neighbours direction in | |
function 'R' -> (position,right) | |
|'L' -> (position,left) | |
|'M' -> ( move state,direction) | |
| _ -> raise (new ArgumentOutOfRangeException()) | |
let executeM initialState commands= List.fold execute initialState commands | |
//parsing | |
let rec batchExecute = let parseC= Char.ToString >> Int32.Parse | |
let parsInit s= ((parseC(List.nth s 0 ), parseC(List.nth s 1 )),direction(List.nth s 2)) | |
function s::commands::tail -> executeM (parsInit s) commands :: batchExecute tail | |
|_ -> [] | |
let executeString (s:String)= let lines=s.Replace(" ","").Split('\n') | |
in batchExecute [for line in lines -> [for c in line -> c]] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment