Skip to content

Instantly share code, notes, and snippets.

@travisby
Last active December 9, 2015 18:38
Show Gist options
  • Save travisby/0fa62b22f860afa01a93 to your computer and use it in GitHub Desktop.
Save travisby/0fa62b22f860afa01a93 to your computer and use it in GitHub Desktop.
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
@ksallberg
Copy link

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

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