Solution for day 17
[?]
Jan 15, 2021, 12:18 AM
KLD6ACAIOYE6WNAEJHASR2MZU4MNIIKM6US56AMASLGGOSD6DEAACDependencies
- [2]
B527MN66Solve day 1 for 2020
Change contents
- file addition: day17.hs[2.17]
{-# LANGUAGE LambdaCase, FlexibleInstances, GADTs, ScopedTypeVariables, TypeApplications #-}import Control.Monadimport Data.Bitsimport Data.Monoid (Endo(..))import Data.Alignimport Data.Theseimport Data.Hashableimport qualified Data.HashMap.Lazy as Mimport qualified Data.HashSet as Simport Data.Proxyimport System.Environmentdata SomeGridType whereSomeGridType :: (Grid a, Neighbourhood a, Eq a, Hashable a) =>Proxy a -> SomeGridTypestep :: (Neighbourhood p, Hashable p, Eq p) => S.HashSet p -> S.HashSet pstep s0 = M.keysSet $M.filter id $alignWith (\caseThis () -> FalseThat n -> n == 3These () n -> n == 2 || n == 3) (S.toMap s0) $M.fromListWith (+) $fmap (flip (,) 1) $S.toList s0 >>= neighboursclass Neighbourhood a whereneighbours :: a -> [a]instance Neighbourhood (Integer,Integer,Integer) whereneighbours = flip map offsets . offset whereoffset ~(x1,y1,z1) ~(x2,y2,z2) = (x1 + x2, y1 + y2, z1 + z2)offsets = filter (/= (0,0,0)) $ (,,) <$>[-1 .. 1] <*>[-1 .. 1] <*>[-1 .. 1]instance Neighbourhood (Integer,Integer,Integer,Integer) whereneighbours = flip map offsets . offset whereoffset ~(x1,y1,z1,w1) ~(x2,y2,z2,w2) = (x1 + x2, y1 + y2, z1 + z2, w1 + w2)offsets = filter (/= (0,0,0,0)) $ (,,,) <$>[-1 .. 1] <*>[-1 .. 1] <*>[-1 .. 1] <*>[-1 .. 1]class Grid a whereonRootPlane :: (Integer,Integer) -> ainstance Grid (Integer,Integer,Integer) whereonRootPlane ~(x,y) = (x,y,0)instance Grid (Integer,Integer,Integer,Integer) whereonRootPlane ~(x,y) = (x,y,0,0)raise :: Monoid a => Int -> a -> araise 0 _ = memptyraise 1 a = araise n a = go1 1 a wherego1 b x| b .&. n == 0 = go1 (shift b 1) (x <> x)| otherwise = go2 (shift b 1) (x <> x) xgo2 b x s = lets' = if b .&. n == 0 then s else x <> sin if countLeadingZeros b == 0 || b >= nthen s'else go2 (shift b 1) (x <> x) s'runBoot :: (Neighbourhood p, Hashable p, Eq p) => S.HashSet p -> S.HashSet prunBoot = appEndo $ raise 6 $ Endo stepreadConfig :: (Grid p, Hashable p, Eq p) => String -> S.HashSet preadConfig s = S.fromList $ do(l,y) <- zip (lines s) [0 ..](c,x) <- zip l [0 ..]guard (c == '#')return $ onRootPlane (x,y)main = do[d,fn] <- getArgsletgt = case d of"3" -> SomeGridType (Proxy @(Integer,Integer,Integer))"4" -> SomeGridType (Proxy @(Integer,Integer,Integer,Integer))case gt ofSomeGridType (_ :: Proxy g) -> doc <- readConfig @g <$> readFile fnprint $ S.size $ runBoot c