wvogel日記

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

hit and blow

hit and blowをHaskellで書いてみた。
なんて素直な書き方なんでしょう

import Control.Monad

main = do cs <- getContents
          forM_ (map (hit_blow 0 (0,0). words) $ lines cs) print'

print' :: (Int,Int) -> IO()
print' (h,b) = putStrLn $ (show h)++" "++(show b)

hit_blow :: Int -> (Int,Int) -> [String] -> (Int,Int)
hit_blow 4 (h,b) _ = (h,b)
hit_blow n (h,b) (x:y:_)= case any (== x!!n) y of
                      True  -> if x!!n == y!!n
                                  then hit_blow (n+1) (h+1,b) (x:[y])
                                  else hit_blow (n+1) (h,b+1) (x:[y])
                      False -> hit_blow (n+1) (h,b) (x:[y])