Last active
December 9, 2015 18:38
-
-
Save travisby/0fa62b22f860afa01a93 to your computer and use it in GitHub Desktop.
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
module Main where | |
import Data.Maybe | |
import Data.List | |
main = do | |
content <- getContents | |
let boxes = map (fromJust . strToBox) $ lines content | |
putStr "Paper: " | |
print . sum . map boxToPaper $ boxes | |
putStr "Ribbon: " | |
print . sum . map boxToRibbon $ boxes | |
data Box = Box Int Int Int deriving (Show) | |
boxToPaper :: Box -> Int | |
boxToPaper (Box l w h) = 2 * a + 2 * b + 2 * c + minimum [a,b,c] | |
where a = l * w | |
b = w * h | |
c = h * l | |
boxToRibbon :: Box -> Int | |
boxToRibbon (Box l w h) = 2 * (!!) sorted 0 + 2 * (!!) sorted 1 + l * w * h | |
where sorted = sort [l, w, h] | |
strToBox :: String -> Maybe Box | |
strToBox str | |
| length splits == 3 = Just $ Box (read $ (!!) splits 0) (read $ (!!) splits 1) (read $ (!!) splits 2) | |
| otherwise = Nothing | |
where splits = split str 'x' | |
split :: String -> Char -> [String] | |
split xs x = foldr (splitOne x) [] xs | |
splitOne :: Char -> Char -> [String] -> [String] | |
splitOne _ x [] = [[x]] | |
splitOne a b (x:xs) | |
| a == b = []:x:xs | |
| otherwise = (b:x):xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like that you have a Box datatype, didn't think of introducing that. You could have avoided the excessive use of the (!!) operator by binding l, w, h to the values as early as possible. See https://github.com/ksallberg/lekstugan/blob/master/adventofcode/Day2_2.hs