Improve some code

This commit is contained in:
Daniele Fucini
2024-12-23 19:00:08 +01:00
parent 588b1e212f
commit a3eab35785
7 changed files with 36 additions and 45 deletions

View File

@@ -1,10 +1,10 @@
{-# OPTIONS_GHC -Wno-x-partial #-}
module Day12 (day12_1) where
import Data.Foldable (toList)
import Data.Graph (Tree, Vertex, graphFromEdges, scc)
import Data.List (uncons)
import Data.List.Split (chunksOf)
import Data.Maybe (fromJust)
type Coords = (Int, Int)
@@ -16,12 +16,12 @@ getValue grid (i, j) = grid !! i !! j
getEdges :: [[V]] -> Coords -> [Int]
getEdges grid (i, j) =
let value = fst $ grid !! i !! j
adjI = filter (\x -> fst x >= 0 && fst x < length grid && snd x >= 0 && snd x < length (fst . fromJust $ uncons grid)) [(i, j + 1), (i + 1, j), (i, j - 1), (i - 1, j)]
in [snd x | x <- map (getValue grid) adjI, (fst . fromJust $ uncons value) == (fst . fromJust $ uncons (fst x))]
adjI = filter (\x -> fst x >= 0 && fst x < length grid && snd x >= 0 && snd x < length (head grid)) [(i, j + 1), (i + 1, j), (i, j - 1), (i - 1, j)]
in [snd x | x <- map (getValue grid) adjI, head value == head (fst x)]
listVertices :: [String] -> [[V]]
listVertices grid =
let l = length $ fst . fromJust $ uncons grid
let l = length $ head grid
in chunksOf l $ zip (map (: []) (concat grid)) [0 ..]
calculatePerimeter :: (Vertex -> (String, Vertex, [Vertex])) -> Tree Vertex -> Int
@@ -34,7 +34,7 @@ day12_1 :: IO ()
day12_1 = do
contents <- lines <$> readFile "input/day12.txt"
let grid = listVertices contents
edgeCoords = [(x, y) | x <- [0 .. length grid - 1], y <- [0 .. length (fst . fromJust $ uncons grid) - 1]]
edgeCoords = [(x, y) | x <- [0 .. length grid - 1], y <- [0 .. length (head grid) - 1]]
edgeList = [(x, y, z) | ((x, y), z) <- zip (concat grid) (map (getEdges grid) edgeCoords)]
(graph, nodeFromVertex, _) = graphFromEdges edgeList
plots = scc graph