never executed always true always false
1 {-|
2 Module: Y2021.D07
3 Description: Advent of Code 2021 Day 07 Solutions.
4 License: MIT
5 Maintainer: @tylerjl
6
7 Solutions to the 2021 day 07 set of problems for <adventofcode.com>.
8 -}
9 module Y2021.D07 where
10
11 import Data.Attoparsec.Text hiding (take)
12 import Data.Either.Utils (fromRight)
13 import Data.Text (Text)
14
15 -- |Solve part A
16 part7A :: Text -> Int
17 part7A = solve7 id . parseCrabs
18
19 -- |Solve part B
20 part7B :: Text -> Int
21 part7B = solve7 crabCost . parseCrabs
22
23 -- |Function to accept a given `Int` and return the sum of an origin point to
24 -- the given `Int`. Suitable for memoization... I think?
25 crabCost :: Int -> Int
26 crabCost n = (n * (n + 1)) `div` 2
27
28 -- |Higher-order function to find the lowest fuel cost.
29 solve7 :: (Ord a, Ord b, Enum b, Num a, Num b) => (b -> a) -> [b] -> a
30 solve7 f crabs = minimum $ map costTo [0..maximum crabs]
31 where costTo crab = sum [ (f . abs) (crab - dest) | dest <- crabs ]
32
33 -- |Parse puzzle input into a list of `Int`s with faster attoparsec.
34 parseCrabs :: Text -> [Int]
35 parseCrabs = fromRight . parseOnly parser
36 where parser = decimal `sepBy` char ',' <* endOfLine