wvogel日記

自分用の技術備忘録が多めです.

AOJ try!(3)

ttp://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0502
にある問題。
本来は、連続して入力を受け付けるのですが、それは愛嬌。

リストだけでも解けるけれど、Stateモナドの練習がてら。

import Control.Monad.State

type PlayState = ([Int],Int)
type DiceSum = Int

start = ([1,2,3,4,5,6],1)

main = do n <- getLine
          cs <-getContents
          print $ evalState (dice.take (read n) $ lines cs) start

dice :: [String] -> State PlayState DiceSum
dice [] = do (_,value) <- get
             return value
dice (c:cs) = do (now,value) <- get
                 put (switch c now,value + head (switch c now))
                 dice cs

switch :: String -> [Int] -> [Int]
switch command [a,b,c,d,e,f] = case command of
                                 "North" -> [b,f,c,d,a,e]
                                 "South" -> [e,a,c,d,f,b]
                                 "East"  -> [d,b,a,f,e,c]
                                 "West"  -> [c,b,f,a,e,d]
                                 "Right" -> [a,c,e,b,d,f]
                                 "Left"  -> [a,d,b,e,c,f]