Day 12 - removed old solution in favour of graph-based solution

This commit is contained in:
Jonathan Chan 2017-12-16 11:12:40 -08:00
parent 3921c021d2
commit 871855ff85
2 changed files with 5 additions and 35 deletions

26
12.hs
View File

@ -1,30 +1,14 @@
import Data.List.Split (splitOn) import Data.List.Split (splitOn)
import Data.IntMap (IntMap, findWithDefault, keys) import Data.Graph (reachable, scc)
import Data.IntSet (IntSet, member, notMember, insert, delete, empty, size, findMin) import Data.Array (array)
import qualified Data.IntMap as M (fromList)
import qualified Data.IntSet as S (fromList, null)
parseLine :: String -> (Int, [Int]) parseLine :: String -> (Int, [Int])
parseLine str = parseLine str =
let src : dests : [] = splitOn " <-> " str let src : dests : [] = splitOn " <-> " str
in (read src, map read $ splitOn ", " dests) in (read src, map read $ splitOn ", " dests)
visit :: IntMap [Int] -> Int -> IntSet -> IntSet
visit hashmap node hashset =
let neighbours = filter (`notMember` hashset) $ findWithDefault [] node hashmap
in foldr (visit hashmap) (foldr insert hashset neighbours) neighbours
remove :: IntMap [Int] -> Int -> IntSet -> IntSet
remove hashmap node hashset =
let neighbours = filter (`member` hashset) $ findWithDefault [] node hashmap
in foldr (remove hashmap) (foldr delete hashset neighbours) neighbours
countGroups :: IntMap [Int] -> Int -> IntSet -> Int
countGroups hashmap count hashset = if S.null hashset then count else
countGroups hashmap (count + 1) $ remove hashmap (findMin hashset) hashset
main :: IO () main :: IO ()
main = do main = do
hashmap <- fmap (M.fromList . map parseLine . lines) $ readFile "12.txt" graph <- fmap (array (0, 1999) . map parseLine . lines) $ readFile "12.txt"
print $ size $ visit hashmap 0 empty print $ length $ reachable graph 0
print $ countGroups hashmap 0 . S.fromList . keys $ hashmap print $ length $ scc graph

View File

@ -1,14 +0,0 @@
import Data.List.Split (splitOn)
import Data.Graph (reachable, scc)
import Data.Array (array)
parseLine :: String -> (Int, [Int])
parseLine str =
let src : dests : [] = splitOn " <-> " str
in (read src, map read $ splitOn ", " dests)
main :: IO ()
main = do
graph <- fmap (array (0, 1999) . map parseLine . lines) $ readFile "12.txt"
print $ length $ reachable graph 0
print $ length $ scc graph