aoc/app/12.hs

55 lines
1.6 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:47:05 +00:00
type Pos = (Int,Int)
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:47:05 +00:00
getGroup :: Pos -> Matrix Char -> [Pos]
2024-12-12 09:38:09 +00:00
getGroup (i,j) s =
let e = getElem i j s in
go e [(i,j)] []
2024-12-12 09:47:05 +00:00
where go :: Char -> [Pos] -> [Pos] -> [Pos]
2024-12-12 09:38:09 +00:00
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:47:05 +00:00
groups :: Matrix Char -> [[Pos]]
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:47:05 +00:00
where go :: [Pos] -> [[Pos]] -> [[Pos]]
2024-12-12 09:14:09 +00:00
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
2024-12-12 09:47:05 +00:00
perimeter :: [Pos] -> Int
2024-12-12 09:14:09 +00:00
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
2024-12-12 09:47:05 +00:00
sides :: [Pos] -> Int
sides s = length $ go s []
where go :: [Pos] -> [(Pos,Pos)] -> [(Pos,Pos)]
go [] v = v
go ((y,x):xs) v
| any (\((y1,x1),(y2,x2)) -> (x == x1 && y1 <= y && y <= y2) || (y == y1 && x1 <= x && x <= x2)) v = go xs v
| otherwise = undefined
2024-12-12 09:14:09 +00:00
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)