summaryrefslogtreecommitdiff
path: root/2021
diff options
context:
space:
mode:
Diffstat (limited to '2021')
-rw-r--r--2021/11.hs36
-rw-r--r--2021/11.in10
2 files changed, 38 insertions, 8 deletions
diff --git a/2021/11.hs b/2021/11.hs
index cf23cec..ff01e17 100644
--- a/2021/11.hs
+++ b/2021/11.hs
@@ -1,15 +1,16 @@
-{-# OPTIONS -Wno-type-defaults #-}
+{-# LANGUAGE MultiWayIf #-}
module Main where
import qualified Data.Array as A
-import Data.List
-import Data.Maybe
+import Data.List (findIndex)
+import Data.Maybe (fromJust)
+import Data.Monoid (Sum(..))
import Input
-stencil8 :: (a -> [a] -> b) -> a -> A.Array (Int, Int) a -> A.Array (Int, Int) b
-stencil8 f def arr =
+stencil8 :: a -> (a -> [a] -> b) -> A.Array (Int, Int) a -> A.Array (Int, Int) b
+stencil8 def f arr =
A.listArray (A.bounds arr)
[f (arr A.! (y, x))
[get (yi, xi)
@@ -22,10 +23,29 @@ stencil8 f def arr =
| otherwise = def
((y1, x1), (y2, x2)) = A.bounds arr
-step1 :: A.Array (Int, Int) Int -> A.Array (Int, Int) Int
-step1 = stencil _ 0
+amap :: A.Ix i => (a -> b) -> A.Array i a -> A.Array i b
+amap f a = A.listArray (A.bounds a) (map f (A.elems a))
+
+flash :: A.Array (Int, Int) Int -> A.Array (Int, Int) Int
+flash = stencil8 0 $ \v env -> if | v < 0 -> v
+ | v > 9 -> -1
+ | otherwise -> v + sum (map (fromEnum . (>9)) env)
+
+step :: A.Array (Int, Int) Int -> (Sum Int, A.Array (Int, Int) Int)
+step a =
+ let a' = fixpoint flash (amap (+1) a)
+ in (Sum (length [() | -1 <- A.elems a']), amap (\v -> if v < 0 then 0 else v) a')
+ where fixpoint f x = let y = f x in if y == x then x else fixpoint f y
+
+display :: A.Array (Int, Int) Int -> String
+display arr = unlines
+ [concat [show (arr A.! (y, x)) | x <- [x1..x2]] | y <- [y1..y2]]
+ where ((y1, x1), (y2, x2)) = A.bounds arr
main :: IO ()
main = do
inp <- getInput 11
- return ()
+ let arr0 = A.listArray ((1, 1), (length inp, length (head inp))) (concatMap (map (read . pure)) inp)
+ let states = iterate (>>= step) (return arr0)
+ print (getSum (fst (states !! 100)))
+ print (fromJust $ findIndex (all (== 0) . A.elems) (map snd states))
diff --git a/2021/11.in b/2021/11.in
new file mode 100644
index 0000000..07abafe
--- /dev/null
+++ b/2021/11.in
@@ -0,0 +1,10 @@
+3322874652
+5636588857
+7755117548
+5854121833
+2856682477
+3124873812
+1541372254
+8634383236
+2424323348
+2265635842