Created
April 4, 2012 14:34
-
-
Save dradtke/2301847 to your computer and use it in GitHub Desktop.
Alternate solution for store credit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Data.List | |
| 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 Eq Item where | |
| (==) item1 item2 = (price item1) == (price item2) | |
| (/=) item1 item2 = (price item1) /= (price item2) | |
| instance Ord Item where | |
| compare item1 item2 | |
| | (price item1) < (price item2) = LT | |
| | (price item1) > (price item2) = GT | |
| | otherwise = EQ | |
| (<) item1 item2 = (price item1) < (price item2) | |
| (>=) item1 item2 = (price item1) >= (price item2) | |
| (>) item1 item2 = (price item1) > (price item2) | |
| (<=) item1 item2 = (price item1) <= (price item2) | |
| max item1 item2 = if (price item1) > (price item2) then item1 else item2 | |
| min item1 item2 = if (price item1) < (price item2) then item1 else item2 | |
| 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 = sort $ zipWith Item [1..] prices | |
| list = shrink credit items | |
| (res1,res2) = (index $ head list,index $ last list) | |
| ans = (show $ min res1 res2) ++ " " ++ (show $ max res1 res2) | |
| shrink :: Int -> [Item] -> [Item] | |
| shrink credit items | |
| | sum < credit = shrink credit $ tail items | |
| | sum > credit = shrink credit $ init items | |
| | otherwise = items | |
| where sum = (price $ head items) + (price $ last items) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment