adventofcode/2021/day13.hs

39 lines
1.2 KiB
Haskell

module Day13 where
import Data.List.Split (splitOn)
import Data.List (nub, sort)
import qualified Data.HashSet as S
import Debug.Trace (trace)
type Dot = (Int,Int)
data Fold = Vertical Int | Horizontal Int deriving Show
parse :: String -> Dot
parse s = (read x, read y) where [x,y] = splitOn "," s
parseFold :: String -> Fold
parseFold s = if axis == "x" then Horizontal (read line) else Vertical (read line) where [axis,line] = splitOn "=" $ last (words s)
fold :: Fold -> Dot -> Dot
fold (Vertical f) (x,y) = (x, if y > f then f - (y-f) else y)
fold (Horizontal f) (x,y) = (if x > f then f - (x-f) else x, y)
main :: IO ()
main = do
input <- lines <$> getContents
let [dots',folds'] = splitOn [""] input
let dots = map parse dots'
let folds = map parseFold folds'
putStr "part 1: "
let dots1 = S.fromList $ map (fold (head folds)) dots
print $ S.size dots1
putStrLn "part 2: "
let dots2 = S.fromList $ map (\d -> foldl (flip fold) d folds) dots
let max_x = maximum $ S.map fst dots2
let max_y = maximum $ S.map snd dots2
mapM_ (\y -> do
mapM_ (\x -> putChar (if (x,y) `S.member` dots2 then '#' else '.')) [0..max_x]
putStrLn ""
) [0..max_y]