--- 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
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]]
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]]
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]
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)