Created
January 2, 2013 09:41
-
-
Save anonymous/4433307 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import Data.List (foldl') | |
import Data.List.Split (chunksOf) | |
-- Main: | |
main :: IO () | |
main = print $ runAll input == output | |
-- Test-Data: | |
input :: String | |
input = unlines [ "5 5" | |
, "1 2 N" | |
, "LMLMLMLMM" | |
, "3 3 E" | |
, "MMRMMRMRRM" ] | |
output :: String | |
output = unlines [ "1 3 N" | |
, "5 1 E" ] | |
-- Data Types: | |
data Rover = Rover { x_ :: Int | |
, y_ :: Int | |
, facing_ :: Direction } | |
data Direction = N | S | E | W deriving (Show, Read) | |
data Command = L | R | M deriving (Show, Read) | |
instance Show Rover where show (Rover x y d) = unwords [show x, show y, show d] | |
-- Libraries: | |
update :: Rover -> Command -> Rover | |
update (Rover x y N) L = Rover x y W | |
update (Rover x y S) L = Rover x y E | |
update (Rover x y E) L = Rover x y N | |
update (Rover x y W) L = Rover x y S | |
update (Rover x y N) R = Rover x y E | |
update (Rover x y S) R = Rover x y W | |
update (Rover x y E) R = Rover x y S | |
update (Rover x y W) R = Rover x y N | |
update (Rover x y N) M = Rover x (succ y) N | |
update (Rover x y S) M = Rover x (pred y) S | |
update (Rover x y E) M = Rover (succ x) y E | |
update (Rover x y W) M = Rover (pred x) y W | |
runRover :: Rover -> [Command] -> Rover | |
runRover = foldl' update | |
parseCommands :: String -> [Command] | |
parseCommands = map (read . return) | |
parseRover :: String -> Rover | |
parseRover s = case words s of [x,y,d] -> Rover (read x) (read y) (read d) | |
_ -> error $ "Invalid rover: " ++ s | |
parseDimensions :: String -> (Int, Int) | |
parseDimensions s = case words s of [x,y] -> (read x, read y) | |
_ -> error $ "Invalid dimensions: " ++ s | |
run :: [String] -> Rover | |
run [l1,l2] = runRover (parseRover l1) (parseCommands l2) | |
run s = error $ "Invalid Run String: " ++ unwords s | |
runAll :: String -> String | |
runAll = unlines . map (show . run) . chunksOf 2 . drop 1 . lines |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment