Skip to content

Instantly share code, notes, and snippets.

@borman
Created April 15, 2012 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borman/2394574 to your computer and use it in GitHub Desktop.
Save borman/2394574 to your computer and use it in GitHub Desktop.
Code Jam 2012 Qualification
import qualified Data.Map as M
subst = [('a','y'),('b','n'),
('c','f'),('d','i'),
('e','c'),('f','w'),
('g','l'),('h','b'),
('i','k'),('j','u'),
('k','o'),('l','m'),
('m','x'),('n','s'),
('o','e'),('p','v'),
('q','z'),('r','p'),
('s','d'),('t','r'),
('u','j'),('v','g'),
('w','t'),('x','h'),
('y','a'),('z','q')]
substTo = M.fromList subst
substFrom = M.fromList $ map (\(a, b) -> (b, a)) subst
crypt t s = zipWith join s new
where
new = map (\x -> M.lookup x t) s
join a Nothing = a
join a (Just b) = b
encrypt = crypt substTo
decrypt = crypt substFrom
solveFile s = concat . map (\(n,s) -> "Case #"++show n++": "++s++"\n") $ l
where
n = (read . head . lines $ s) :: Int
l = zip [1..] $ map decrypt (take n . drop 1 . lines $ s)
main = interact solveFile
import Data.List
-- All distinct pairs
generate a b = [(x, y) | x <- [a..b], y <- [a..b], x < y]
-- Is pair recycled?
test (a,b) = length sa == length sb && isShift sa sb
where
sa = show a
sb = show b
isShift a b = any (isPrefixOf a) . take (length b) . tails . cycle $ b
-- Process input
solve s = unlines . cases . map (show . solveOne) $ tests
where
prep :: [[Int]]
prep = map (map read . words) . lines $ s
t = head . head $ prep
tests = take t . drop 1 $ prep
solveOne [a, b] = length . filter (\x->x) . map test $ generate a b
cases cs = map (\(n,x) -> "Case #"++show n++": "++x) . zip [1..] $ cs
main = interact solve
-- vim: cindent
@klapaucius
Copy link

Бросается в глаза слабое знание стандартной библиотеки. К примеру, \x->x это id, \(a, b) -> (b, a) - Data.Tuple.swap, а concat . map (\(n,s) -> "Case #"++show n++": "++s++"\n") $ l просто (\(n,s) -> "Case #"++show n++": "++s++"\n") =<< l или даже (uncurry $ printf "Case #%d: %s\n") =<< l

@borman
Copy link
Author

borman commented Apr 16, 2012

Насчет слабого знания не могу не согласиться --- практики работы с языком маловато. За практический пример использования list monad отдельное спасибо.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment