2015 Day 15 in Haskell

This commit is contained in:
germax26 2024-12-03 13:21:05 +11:00
parent 0bdd0081bb
commit 10764fdb1b
Signed by: germax26
SSH Key Fingerprint: SHA256:N3w+8798IMWBt7SYH8G1C0iJlIa2HIIcRCXwILT5FvM
2 changed files with 28 additions and 1 deletions

21
2015/day15/day15.hs Normal file
View File

@ -0,0 +1,21 @@
import Aoc
import Data.List ( transpose )
import Data.Bifunctor ( bimap )
parseLine :: String -> (String, [Int])
parseLine line =
let [name, "capacity", capacity, "durability", durability, "flavor", flavor, "texture", texture, "calories", calories] = words line in
let read' = read . init in
(init name, [read calories, read' capacity, read' durability, read' flavor, read' texture])
part1' :: (Int -> Bool) -> [(String, [Int])] -> Int
part1' cond ingredients = maximum $ map (product . tail) $ filter (cond . head) $ map (map (max 0 . sum) . transpose . map (uncurry map . bimap (*) snd) . (`zip` ingredients)) $ starsAndBars 100 (length ingredients - 1)
part1 :: [(String, [Int])] -> Int
part1 = part1' $ const True
part2 :: [(String, [Int])] -> Int
part2 = part1' (==500)
main :: IO ()
main = aocMain (map parseLine) part1 part2

6
aoc.hs
View File

@ -51,3 +51,9 @@ permutations xs = concatMap (\n -> let (a, rest) = remove n xs in map (a:) $ per
adjacents :: [a] -> [(a, a)]
adjacents as = zip as $ tail as
-- starsAndBars n b returns all lists of non-negative integers of length `b+1` where the sum is `n`
starsAndBars :: Int -> Int -> [[Int]]
starsAndBars 0 b = [replicate (b+1) 0]
starsAndBars n 0 = [[n]]
starsAndBars n b = map (0:) (starsAndBars n (b-1)) ++ map (\xs -> head xs + 1 : tail xs) (starsAndBars (n-1) b)