Created
February 28, 2023 05:53
-
-
Save presci/32797c319c9ee224e8ad3ac902341cdc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import qualified Data.Vector as V | |
import Data.Maybe | |
data IsNew = N|O deriving (Show) | |
data Cell = Cell Int Int IsNew deriving (Show) | |
instance Eq Cell where | |
(==) (Cell x0 y0 _) (Cell x1 y1 _) = x0 == x1 && y0 == y1 | |
ltoV::[a]-> V.Vector a | |
ltoV = V.fromList | |
conv::String -> V.Vector Int | |
conv = ltoV . map (read::String -> Int) . words | |
countIsland :: V.Vector (V.Vector Int) -> [Cell] | |
countIsland island = islandhelper1 (0, 0) [] | |
where | |
islandhelper1::(Int, Int) -> [Cell] -> [Cell] | |
islandhelper1 a@(x, y) g = case island V.!? x of | |
Just row -> islandhelper2 row a g | |
_ -> g | |
islandhelper2:: V.Vector Int -> (Int, Int) -> [Cell] -> [Cell] | |
islandhelper2 xss (x, y) g = case xss V.!? y of | |
Just 1 -> islandhelper2 xss (x, y+ 1) (Cell x y O:g) | |
Just 0 -> islandhelper2 xss (x, y+1) g | |
_ -> islandhelper1 (x+ 1, 0) g | |
removeNbs:: [Cell] -> [Cell] | |
removeNbs [] = [] | |
removeNbs (x:xss) = removeNbs1 [x] xss | |
where | |
removeNbs1 :: [Cell]->[Cell] -> [Cell] | |
removeNbs1 [] g = g | |
removeNbs1 (x:xss) g = let acc = (merge fm xss) in removeNbs1 acc (filter (==x) g) | |
where | |
fm :: [Cell] | |
fm = mapMaybe getnbs [(0,1), (1,0), (0, -1), (-1, 0)] | |
getnbs ::(Int, Int) -> Maybe Cell | |
getnbs (x, y) = if Cell x y O `elem` g then Just (Cell x y O) else Nothing | |
merge :: [Cell] -> [Cell] -> [Cell] | |
merge [] g = g | |
merge g [] = g | |
merge (x:xss) y = merge (x:y) xss | |
main::IO() | |
main = do | |
content <- ltoV . map conv . lines <$> readFile "input.txt" | |
print . removeNbs . countIsland $ content |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment