Now faster
This commit is contained in:
parent
c54080fdc6
commit
769d144b77
23
app/12.hs
23
app/12.hs
@ -5,24 +5,29 @@ import Data.Functor
|
||||
import Data.Matrix hiding (trace)
|
||||
import Data.List
|
||||
import Debug.Trace
|
||||
import Data.Maybe
|
||||
|
||||
parse :: String -> Matrix Char
|
||||
parse = fromLists . lines
|
||||
|
||||
getGroup :: (Int,Int) -> Matrix Char -> [(Int,Int)] -> [(Int,Int)]
|
||||
getGroup p@(i,j) s v
|
||||
| p `elem` v = v
|
||||
| otherwise = let e = getElem i j s in
|
||||
nub . (p:) $ filter((== Just e) . flip (uncurry safeGet) s) [(i,j+1),(i,j-1),(i+1,j),(i-1,j)] >>= \p' -> getGroup p' s (p:v)
|
||||
where
|
||||
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)
|
||||
|
||||
groups :: Matrix Char -> [[(Int,Int)]]
|
||||
groups s = nub $ go [(i,j) | i <- [1 .. nrows s], j <- [1 .. ncols s]] []
|
||||
groups s = go [(i,j) | i <- [1 .. nrows s], j <- [1 .. ncols s]] []
|
||||
where go :: [(Int,Int)] -> [[(Int,Int)]] -> [[(Int,Int)]]
|
||||
go [] v = v
|
||||
go (x:xs) v
|
||||
| any (x `elem`) v = go xs v
|
||||
| otherwise = go xs (getGroup x s []:v)
|
||||
| otherwise = go xs (nub (getGroup x s):v)
|
||||
|
||||
perimeter :: [(Int,Int)] -> Int
|
||||
perimeter s = length $ s >>= \(i,j) -> [(i,j+1),(i,j-1),(i+1,j),(i-1,j)] \\ s
|
||||
@ -34,6 +39,6 @@ solve2 :: Matrix Char -> Int
|
||||
solve2 = undefined
|
||||
|
||||
main :: IO ()
|
||||
main = readFile "inputs/12.example" <&> parse >>= \i ->
|
||||
main = readFile "inputs/12" <&> parse >>= \i ->
|
||||
print (solve1 i) >>
|
||||
print (solve2 i)
|
||||
|
Loading…
Reference in New Issue
Block a user