George Thomas 415055dcc2 Allow output types to vary for different parts of same day
For now this applies to Haskell only, and it may turn out to be tricky for the Rust implementation.

In practice, the limitation hasn't turned out to be important, and we could even go the other way and use `Integer` everywhere. This does however at least help with debugging, as well as just being conceptually right.

The `nil` and `(/\)` functions are intended to be overloaded to work for other list-like things in a later commit, and from there we will investigate using `OverloadedLists` and `RebindableSyntax` to recover standard list syntax, although there are probably limitations due to `(:)` being special.
2025-12-16 16:15:11 +00:00

52 lines
1.3 KiB
Haskell

module Puzzles.Day5 (puzzle) where
import Pre
puzzle :: Puzzle
puzzle =
Puzzle
{ number = 5
, parser = const do
ranges <- (Range <$> decimal <* single '-' <*> decimal) `sepEndBy` newline
void newline
vals <- decimal `sepEndBy` newline
pure (ranges, vals)
, parts =
( \(ranges, vals) ->
length
. filter (flip any ranges . isInRange)
$ vals
)
/\ ( sum
. map rangeLength
. foldr addInterval []
. sortOn (Down . (.lower))
. fst
)
/\ nil
, extraTests = mempty
}
data Range = Range
{ lower :: Int
, upper :: Int
}
deriving (Eq, Ord, Show)
rangeLength :: Range -> Int
rangeLength r = r.upper - r.lower + 1
isInRange :: Int -> Range -> Bool
isInRange n r = n >= r.lower && n <= r.upper
extend :: Int -> Range -> Range
extend upper r = r{upper = max r.upper upper}
addInterval :: Range -> [Range] -> [Range]
addInterval new = \case
[] -> [new]
(r : rs) ->
if isInRange new.lower r
then extend new.upper r : rs
else new : r : rs