Google Code Jam/Alien Numbers

From HaskellWiki
< Google Code Jam
Revision as of 07:07, 29 June 2008 by Paolino (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

import Data.List import Data.Maybe number :: String -> String -> Integer number ks xs = let z c = fromIntegral $ fromJust (findIndex ( == c) ks) in fst $ foldr (\x (n,m) -> (z x * m + n ,m * fromIntegral (length ks))) (0,1) xs string :: String -> Integer -> String string ks n = let s = fromIntegral $ length ks in reverse $ unfoldr (\x -> let (f,g) = divMod x s in if x == 0 then Nothing else Just (ks !! (fromInteger g),f)) n type Question = (String,String,String) answer :: Question -> String answer (num,base,target) = string target (number base num) parseQuestion :: String -> Question parseQuestion x = let [num,base,target] = words $ x in (num,base,target) parseCases :: String -> [Question] parseCases x = let (n:ts) = lines x in take (read n) . map parseQuestion $ ts main = do ts <- parseCases `fmap` getContents flip mapM_ (zip [1..] ts) $ \(i,t) -> do putStr $ "Case #" ++ show i ++ ": " putStrLn $ answer t