Skip to content

Commit c4fb583

Browse files
committed
Add solution to second part of day12
1 parent c2f354a commit c4fb583

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

day12/src/Main.hs

+24-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import Data.Char (isLower)
2+
import Data.List (nub)
23
import Data.List.Split (splitOn)
34
import Data.Map as M (Map, empty, insertWith, (!))
45

@@ -14,6 +15,8 @@ main = do
1415
input <- readInput "day12/input"
1516
print $ "Test input: " ++ show (firstProblem testInput) ++ " == 10"
1617
print $ "Problem input: " ++ show (firstProblem input) ++ " == 3738"
18+
print $ "Test input: " ++ show (secondProblem testInput) ++ " == 36"
19+
print $ "Problem input: " ++ show (secondProblem input) ++ " == 120506"
1720
where
1821
readInput file = foldl foldLine M.empty . lines <$> readFile file
1922
foldLine acc = insertNew acc . splitOn "-"
@@ -28,16 +31,32 @@ isSmall = isLower . head
2831

2932
type CaveConections = Map Cave [Cave]
3033

34+
type Path = [Cave]
35+
3136
firstProblem :: CaveConections -> Int
32-
firstProblem = length . getPaths
37+
firstProblem = problem caveFilter
38+
where
39+
caveFilter path cave = not $ isSmall cave && elem cave path
40+
41+
secondProblem :: CaveConections -> Int
42+
secondProblem = problem caveFilter
43+
where
44+
caveFilter path cave =
45+
let visitedSmallTwice = (\a -> length (nub a) /= length a) $ filter isSmall path
46+
in if visitedSmallTwice
47+
then not $ isSmall cave && elem cave path
48+
else cave /= "start"
49+
50+
problem :: (Path -> Cave -> Bool) -> CaveConections -> Int
51+
problem predicate = length . getPaths predicate
3352

34-
getPaths :: CaveConections -> [[String]]
35-
getPaths connections = getPaths' ["start"]
53+
getPaths :: (Path -> Cave -> Bool) -> CaveConections -> [Path]
54+
getPaths predicate connections = getPaths' ["start"]
3655
where
3756
getPaths' path@("end" : _) = [reverse path]
3857
getPaths' path =
39-
let possibleMovements = filterSmall path $ connections ! head path
58+
let possibleMovements = filterByPredicate path $ connections ! head path
4059
in if null possibleMovements
4160
then []
4261
else concatMap (getPaths' . (: path)) possibleMovements
43-
filterSmall path = filter $ not . (\cave -> isSmall cave && elem cave path)
62+
filterByPredicate path = filter $ predicate path

0 commit comments

Comments
 (0)