Skip to content

Instantly share code, notes, and snippets.

@dradtke
Created March 27, 2012 22:12
Show Gist options
  • Select an option

  • Save dradtke/2220863 to your computer and use it in GitHub Desktop.

Select an option

Save dradtke/2220863 to your computer and use it in GitHub Desktop.
Haskell Solution for Store Credit (Google Code Jam)
type Input = [String]
data Unsolved = Unsolved { unsolvedNumber :: Int, input :: Input }
data Solved = Solved { solvedNumber :: Int, answer :: String }
data Item = Item { index :: Int, price :: Int }
instance Show Solved where
show (Solved n ans) = "Case #" ++ (show n) ++ ": " ++ ans
instance Show Item where
show (Item index price) = show index
main :: IO ()
main = do
input <- fmap (tail.lines) getContents
let cases = zipWith Unsolved [1..] (splitIntoCases input)
mapM_ putStrLn $ map (show.solve) cases
splitIntoCases :: [String] -> [Input]
splitIntoCases input
| post == [] = [pre]
| otherwise = pre:(splitIntoCases post)
where (pre,post) = splitAt 3 input
solve :: Unsolved -> Solved
solve (Unsolved n input) = Solved n ans
where (l1:l2:l3:_) = input
credit = read l1 :: Int
prices = map read $ words l3 :: [Int]
items = zipWith Item [1..] prices
(res1,res2) = head [(item1,item2) |
item1 <- items, item2 <- items,
(index item1) < (index item2),
(price item1) + (price item2) == credit]
ans = (show res1) ++ " " ++ (show res2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment