diff --git a/src/Javran/AdventOfCode/Y2023/Day5.hs b/src/Javran/AdventOfCode/Y2023/Day5.hs index 182820b8..83d559b8 100644 --- a/src/Javran/AdventOfCode/Y2023/Day5.hs +++ b/src/Javran/AdventOfCode/Y2023/Day5.hs @@ -46,8 +46,29 @@ almanacP = do many entryP pure (seeds, rs) +mkMapper :: AlmanacMap -> Int -> Int +mkMapper xs = auxLookup + where + -- key: src, value: (dst, range) + m :: IM.IntMap (Int, Int) + m = IM.fromList do + (dst, src, rng) <- xs + pure (src, (dst, rng)) + + -- rely on split and maxView on left result to do our work + auxLookup i + | Just (dst, _) <- cur = dst + | Just ((src, (dst, rng)), _) <- IM.maxViewWithKey lm + , i < src + rng = + dst + (i - src) + | otherwise = i + where + (lm, cur, _) = IM.splitLookup i m + instance Solution Day5 where solutionSolved _ = False solutionRun _ SolutionContext {getInputS, answerShow} = do - xs <- consumeOrDie almanacP <$> getInputS - print xs + (seeds, maps) <- consumeOrDie almanacP <$> getInputS + let fs = fmap mkMapper maps + locs = foldl' (\xs f -> fmap f xs) seeds fs + answerShow (minimum locs)