Skip to content

Commit

Permalink
comments
Browse files Browse the repository at this point in the history
  • Loading branch information
glguy committed Dec 6, 2023
1 parent d49be71 commit ce12bbb
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions solutions/src/2023/05.hs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ ranges and find the lowest bound of the output intervals.
module Main where

import Advent (format, chunks)
import Advent.Box (intersectBox, subtractBox, Box', Box(..))
import Advent.Box (intersectBox, Box', Box(..), subtractBox')
import Control.Exception (assert)
import Control.Monad (foldM)

-- |
--
Expand All @@ -64,8 +65,9 @@ main =
print (smallestDestination maps [interval start 1 | start <- seeds])
print (smallestDestination maps [interval start n | [start,n] <- chunks 2 seeds])

-- | Apply all the maps to all the intervals and return the smallest output
smallestDestination :: [[(Interval, Int)]] -> [Interval] -> Int
smallestDestination maps = lowerBound . minimum . applyMaps maps
smallestDestination maps = lowerBound . minimum . concatMap (applyMaps maps)

-- Verify that all the maps are presented in order
-- This is technically unnecessary for the given inputs, but it feels bad to
Expand All @@ -81,19 +83,17 @@ checkMaps input = foldr processMap finish input "seed"

entryToInterval (dst, src, len) = (interval src len, dst - src)

applyMaps :: [[(Interval, Int)]] -> [Interval] -> [Interval]
applyMaps maps xs =
foldl (\acc ranges -> concatMap (applyMap ranges) acc) xs maps
-- | Apply the rewrite maps left to right to the input interval.
applyMaps :: [[(Interval, Int)]] -> Interval -> [Interval]
applyMaps = flip (foldM (flip applyMap))

-- | Apply a single rewrite map to an input interval.
applyMap :: [(Interval, Int)] -> Interval -> [Interval]
applyMap = foldr applyEntry pure
where
applyEntry (src, delta) continue box =
case intersectBox src box of
Nothing -> continue box
Just i ->
shiftInterval delta i :
concatMap continue (subtractBox src box)
applyMap [] x = [x]
applyMap ((s, d) : m) x =
case intersectBox s x of
Nothing -> applyMap m x
Just i -> shiftInterval d i : concatMap (applyMap m) (subtractBox' i x)

-- Interval specialization of the Box module

Expand Down

0 comments on commit ce12bbb

Please sign in to comment.