Skip to content

Instantly share code, notes, and snippets.

@sordina
Forked from anonymous/Rover.hs
Last active December 10, 2015 12:19
Show Gist options
  • Save sordina/4433320 to your computer and use it in GitHub Desktop.
Save sordina/4433320 to your computer and use it in GitHub Desktop.
import Data.List (foldl')
import Data.List.Split (chunksOf)
-- Main:
main :: IO ()
main = print $ run 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:
-- DRY is for suckahs
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
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
runRover :: [String] -> Rover
runRover [l1,l2] = foldl' update (parseRover l1) (parseCommands l2)
runRover s = error $ "Invalid Run String: " ++ unwords s
run :: String -> String
run = unlines . map (show . runRover) . chunksOf 2 . drop 1 . lines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment