import Control.Lens
import Control.Monad
import Data.List
import Linear.V2
import Linear.V3
import Linear.V4
import Linear.Vector

main :: IO ()
main = do
  input <- lines <$> readFile "input"
  let a = toVec input
      _ = a :: [V4 Int]
--      _ = a :: [V3 Int]
  print $ day17 a

day17 = length . flip (!!) 6 . iterate step

toVec input =
  [ zero & _xy .~ V2 x y
  | (y, line) <- zip [0 ..] input
  , (x, c) <- zip [0 ..] line
  , c == '#'
  ]

step state =
  (nub .
   concatMap fst .
   filter f . ap zip (map length) . group . sort . updateNeighbours)
    state
  where
    f (x, n) = n == 3 || n == 2 && head x `elem` state

updateNeighbours = concatMap f
  where
    f coord =
      [ coord + v
      | v <-
          filter (/= zero) $
          nub $ map sum $ subsequences (ap (++) (map negate) basis)
      ]
