Day 21 part 1
[advent-of-code-21.git] / advent20 / Main.hs
index fbc4fb63ed63df4c1c22c44e380b6a557c6826f5..2c258a758b80a355f698a53551d8c569156e09c5 100644 (file)
@@ -1,5 +1,4 @@
--- Writeup at https://work.njae.me.uk/2021/12/18/advent-of-code-2021-day-16/
-
+-- Writeup at https://work.njae.me.uk/2021/12/23/advent-of-code-2021-day-20/
 
 import Control.Monad.State.Strict
 import Control.Monad.Reader
@@ -44,20 +43,19 @@ enhanceImage 0 = do image <- get
 enhanceImage n = do newImage
                     enhanceImage (n - 1)
 
+
 newImage :: ImageEnhancer ()
 newImage =
-  do  image <- get
-      let region = explicitRegion image
+  do  region <- gets explicitRegion
       let region' = expandRegion region
       let heres = range region'
-      let distant = distantPixel image
-      newPixelStates <- mapM newPixel heres
-      let grid' = S.fromList $ catMaybes newPixelStates
+      newPixels <- mapM newPixel heres
+      let grid' = S.fromList $ catMaybes newPixels
+      distant <- gets distantPixel
       enhancement <- ask
       let distant' = if distant then (last enhancement) else (head enhancement)
       put $ Image {grid = grid', distantPixel = distant', explicitRegion = region'}
 
-
 showImage :: Image -> String
 showImage image = 
   unlines $ [ [showPixel (V2 r c) | c <- [minC..maxC] ] | r <- [minR..maxR]]
@@ -79,12 +77,22 @@ findStencil here =
       d <- gets distantPixel
       r <- gets explicitRegion
       return $ map (findContents g d r) nbrs
+      -- mapM findContents nbrs
 
 findContents :: S.Set Pixel -> Bool -> (Pixel, Pixel) -> Pixel -> Bool
 findContents grid distant region here 
   | inRange region here = here `S.member` grid
   | otherwise           = distant
 
+-- more consitent but much slower
+-- findContents :: Pixel -> ImageEnhancer Bool
+-- findContents here =
+--  do  g <- gets grid
+--      distant <- gets distantPixel
+--      region <- gets explicitRegion
+--      return $ if inRange region here 
+--               then (here `S.member` g)
+--               else distant
 
 neighbours :: [Pixel]
 neighbours = [V2 r c | r <- [-1, 0, 1], c <- [-1, 0, 1]]
@@ -92,6 +100,7 @@ neighbours = [V2 r c | r <- [-1, 0, 1], c <- [-1, 0, 1]]
 expandRegion :: (Pixel, Pixel) -> (Pixel, Pixel)
 expandRegion ((V2 r0 c0), (V2 r1 c1)) = (V2 (r0 - 1) (c0 - 1), V2 (r1 + 1) (c1 + 1))
 
+parse :: String -> (Enhancement, Image)
 parse text = (enhancement, image)
   where ls = lines text
         enhancement = [ c == '#' | c <- head ls]
@@ -106,10 +115,6 @@ mkImage rows = Image { grid = grid, distantPixel = False
         maxCol = (length $ head rows) - 1
         grid = S.fromList [V2 r c | r <- [0..maxRow], c <- [0..maxCol], (rows!!r)!!c == '#']
 
-
+intify :: [Bool] -> Int
 intify pixels = foldl' addBit 0 pixels
   where addBit w b = (w * 2) + (if b then 1 else 0)
-
--- wordify :: BS.BitString -> Integer
--- wordify bs = foldl' addBit 0 $ BS.to01List bs
---   where addBit w b = (w * 2) + (fromIntegral b)