From 91c4402d945cb08abcb7523ccf19155ef10aeea2 Mon Sep 17 00:00:00 2001 From: Tom Smeding Date: Sat, 5 Dec 2026 19:14:38 +0000 Subject: genericise --- 2026/5.hs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) (limited to '2026/5.hs') diff --git a/2026/5.hs b/2026/5.hs index c6b5f49..29e7617 100644 --- a/2026/5.hs +++ b/2026/5.hs @@ -1,6 +1,7 @@ {-# OPTIONS -Wno-x-partial #-} module Main where +import Data.Foldable (toList) import Data.List (foldl') import Data.Set qualified as Set import Data.Set (Set) @@ -33,15 +34,17 @@ press n btn = Bksp -> n `quot` 10 in if n' >= 10000 then n else n' -search :: [Btn] -> Set Int -> Set Int -> Set Int -search _ seen front | Set.null front = seen -search btns seen front = - let seen' = seen <> front - news = Set.fromList [press n b | n <- Set.toList front, b <- btns] Set.\\ seen' - in search btns seen' news +bfs :: (Ord a, Foldable t) => (a -> t a) -> Set a -> Set a +bfs f = go mempty + where + go seen front | Set.null front = seen + go seen front = + let seen' = seen <> front + news = Set.fromList [y | x <- Set.toList front, y <- toList (f x)] Set.\\ seen' + in go seen' news main :: IO () main = do btns <- map (parseBtn . init . tail) . words <$> getContents print . sum . Set.toList $ Set.fromList . map (foldl' press 0) $ cartprod 3 btns - print . sum . Set.toList $ search btns mempty (Set.singleton 0) + print . sum . Set.toList $ bfs (\n -> [press n b | b <- btns]) (Set.singleton 0) -- cgit v1.3.1