2012年6月18日

Haskellでcode jamに挑戦

2012年の予選問題
Problem C. Recycled Numbers

出題範囲の数を全部列挙して、それぞれrecycled numberを作り出して出題範囲に収まっているかどうか調べてからrecycled numberだけを畳み込んで数える

import Data.List

toInteger' s = read s :: Integer

rotate lower upper n = let f1 n = n `div` 10
      f2 n = (n `mod` 10) * 10 ^ (digitcount - 1)
      f3 n = f1 n + f2 n
      digitcount = length $ show n
      rec _ 0 r = length (filter (\x -> x >= lower && x <= upper) $ Data.List.nub r) - 1
      rec n d r = rec (f3 n) (d - 1) ((f3 n) : r)
      in rec n (digitcount - 1) (n:[])

scan lower upper = (foldl' (\acc x -> acc + (rotate lower upper x)) 0 [lower..upper]) `div` 2

compute s = let f = map (toInteger') (words s)
  in scan (head f) (last f)

main = do
 line <- getLine
 contents <- getContents
 putStrLn $ unlines $ map (\(i, line) -> "Case #" ++ show i ++ ": " ++ show (compute line)) $ zip [1..] $ lines contents