Skip to content

Commit c2f354a

Browse files
committed
Add solution to the first part of day12
1 parent 437b13f commit c2f354a

File tree

4 files changed

+78
-0
lines changed

4 files changed

+78
-0
lines changed

AdventOfCode2021.cabal

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,10 @@ executable day11
7171
main-is: Main.hs
7272
build-depends: base ^>=4.14.3.0, matrix, mtl
7373
hs-source-dirs: day11/src
74+
default-language: Haskell2010
75+
76+
executable day12
77+
main-is: Main.hs
78+
build-depends: base ^>=4.14.3.0, containers, split
79+
hs-source-dirs: day12/src
7480
default-language: Haskell2010

day12/input

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
zs-WO
2+
zs-QJ
3+
WO-zt
4+
zs-DP
5+
WO-end
6+
gv-zt
7+
iu-SK
8+
HW-zs
9+
iu-WO
10+
gv-WO
11+
gv-start
12+
gv-DP
13+
start-WO
14+
HW-zt
15+
iu-HW
16+
gv-HW
17+
zs-SK
18+
HW-end
19+
zs-end
20+
DP-by
21+
DP-iu
22+
zt-start

day12/src/Main.hs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import Data.Char (isLower)
2+
import Data.List.Split (splitOn)
3+
import Data.Map as M (Map, empty, insertWith, (!))
4+
5+
{-
6+
Some considerations about the input:
7+
* There can't be two adjacent big caves
8+
* There must be a cave called "start" and another one called "end"
9+
-}
10+
11+
main :: IO ()
12+
main = do
13+
testInput <- readInput "day12/test_input"
14+
input <- readInput "day12/input"
15+
print $ "Test input: " ++ show (firstProblem testInput) ++ " == 10"
16+
print $ "Problem input: " ++ show (firstProblem input) ++ " == 3738"
17+
where
18+
readInput file = foldl foldLine M.empty . lines <$> readFile file
19+
foldLine acc = insertNew acc . splitOn "-"
20+
insertNew map (cave1 : cave2 : _) =
21+
insertWith (++) cave1 [cave2] $ insertWith (++) cave2 [cave1] map
22+
insertNew _ out = error $ "Invalid split: " ++ show out
23+
24+
type Cave = String
25+
26+
isSmall :: Cave -> Bool
27+
isSmall = isLower . head
28+
29+
type CaveConections = Map Cave [Cave]
30+
31+
firstProblem :: CaveConections -> Int
32+
firstProblem = length . getPaths
33+
34+
getPaths :: CaveConections -> [[String]]
35+
getPaths connections = getPaths' ["start"]
36+
where
37+
getPaths' path@("end" : _) = [reverse path]
38+
getPaths' path =
39+
let possibleMovements = filterSmall path $ connections ! head path
40+
in if null possibleMovements
41+
then []
42+
else concatMap (getPaths' . (: path)) possibleMovements
43+
filterSmall path = filter $ not . (\cave -> isSmall cave && elem cave path)

day12/test_input

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
start-A
2+
start-b
3+
A-c
4+
A-b
5+
b-d
6+
A-end
7+
b-end

0 commit comments

Comments
 (0)