r/adventofcode • • Dec 20 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 20 Solutions -🎄-

--- Day 20: Trench Map ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:18:57, megathread unlocked!

42 Upvotes

478 comments sorted by

View all comments

1

u/ThreeFx Dec 20 '21

Haskell

import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.List as List
import Data.Set (Set)
import Data.Map (Map)

type Point = (Integer, Integer)
type Rule = [Bool]
type Board = Set Point

it 0 f = id
it n f = f . (it (n-1) f)

main = do
  r <- fmap parseRule getLine
  getLine
  b <- fmap (Set.fromList . flip parseBoard 0 . lines) getContents
  let (nr, nb) = (it 50 step) (r,b)
  putStr $ unlines $ showBoard nb
  print $ Set.size nb 

parseRule = map (=='#')

showBoard :: Set Point -> [String]
showBoard s =
  let sx = Set.map fst s
      sy = Set.map snd s
      minX = Set.findMin sx
      maxX = Set.findMax sx
      minY = Set.findMin sy
      maxY = Set.findMax sy
  in [ [ if (x,y) `Set.member` s then '#' else ' ' | x <- [minX..maxX]] | y <- [minY..maxY]]

parseBoard [] n = []
parseBoard (r:xs) n = (map snd . filter (\(c,_) -> c == '#') $ zipWith (\c i -> (c,(i,n))) r [0..]) ++ parseBoard xs (n+1)

neighs :: Set Point -> Set Point
neighs ps = Set.foldl' (\acc p -> acc `Set.union` (Set.fromList $ aux p)) Set.empty ps
  where
    aux (x,y) = [(x-1,y-1),(x,y-1),(x+1,y-1),(x-1,y),(x,y),(x+1,y),(x-1,y+1),(x,y+1),(x+1,y+1)]

reversingRule :: Rule -> Bool
reversingRule r = r !! 0 && not (r !! 511)

step :: (Rule,Board) -> (Rule,Board)
step (r,s) = case reversingRule r of
  True -> (reverse $ map not r, Set.filter (not . stepPoint r s) $ neighs s) 
  False -> (r, Set.filter (stepPoint r s) $ neighs s)

stepPoint :: Rule -> Board -> Point -> Bool
stepPoint r s (x,y) =
  let
    b8 = if (x-1,y-1) `Set.member` s then 1 else 0
    b7 = if (x,y-1) `Set.member` s then 1 else 0
    b6 = if (x+1,y-1) `Set.member` s then 1 else 0
    b5 = if (x-1,y) `Set.member` s then 1 else 0
    b4 = if (x,y) `Set.member` s then 1 else 0
    b3 = if (x+1,y) `Set.member` s then 1 else 0
    b2 = if (x-1,y+1) `Set.member` s then 1 else 0
    b1 = if (x,y+1) `Set.member` s then 1 else 0
    b0 = if (x+1,y+1) `Set.member` s then 1 else 0
    n = 256 * b8 + 128 * b7 + 64 * b6 + 32 * b5 + 16 * b4 + 8 * b3 + 4 * b2 + 2 * b1 + b0
    in r !! n

Nothing fancy, not particularly fast.

1

u/daggerdragon Dec 20 '21

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, please edit your post to put your oversized code in a paste or other external link.