aoc/app/12.hs

45 lines
1.3 KiB
Haskell
Raw Normal View History

2024-12-02 10:51:49 +00:00
{-# LANGUAGE LambdaCase #-}
module Main where
import Data.Functor
2024-12-12 09:14:09 +00:00
import Data.Matrix hiding (trace)
import Data.List
import Debug.Trace
2024-12-12 09:38:09 +00:00
import Data.Maybe
2024-12-02 10:51:49 +00:00
2024-12-12 09:14:09 +00:00
parse :: String -> Matrix Char
parse = fromLists . lines
2024-12-02 10:51:49 +00:00
2024-12-12 09:38:09 +00:00
getGroup :: (Int,Int) -> Matrix Char -> [(Int,Int)]
getGroup (i,j) s =
let e = getElem i j s in
go e [(i,j)] []
where go :: Char -> [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)]
go _ [] v = v
go c (x@(i,j):xs) v
| x `elem` v = go c xs v
| uncurry safeGet x s /= Just c = go c xs v
| otherwise = go c (filter (isJust . flip (uncurry safeGet) s) [(i+1,j),(i-1,j),(i,j+1),(i,j-1)] ++ xs) (x:v)
2024-12-02 10:51:49 +00:00
2024-12-12 09:14:09 +00:00
groups :: Matrix Char -> [[(Int,Int)]]
2024-12-12 09:38:09 +00:00
groups s = go [(i,j) | i <- [1 .. nrows s], j <- [1 .. ncols s]] []
2024-12-12 09:14:09 +00:00
where go :: [(Int,Int)] -> [[(Int,Int)]] -> [[(Int,Int)]]
go [] v = v
go (x:xs) v
| any (x `elem`) v = go xs v
2024-12-12 09:38:09 +00:00
| otherwise = go xs (nub (getGroup x s):v)
2024-12-12 09:14:09 +00:00
perimeter :: [(Int,Int)] -> Int
perimeter s = length $ s >>= \(i,j) -> [(i,j+1),(i,j-1),(i+1,j),(i-1,j)] \\ s
solve1 :: Matrix Char -> Int
solve1 s = let g = groups s; p = perimeter <$> g in sum $ zipWith (*) (length <$> g) p
solve2 :: Matrix Char -> Int
2024-12-02 10:51:49 +00:00
solve2 = undefined
main :: IO ()
2024-12-12 09:38:09 +00:00
main = readFile "inputs/12" <&> parse >>= \i ->
2024-12-02 10:51:49 +00:00
print (solve1 i) >>
print (solve2 i)