Skip to content

Commit 2c39724

Browse files
committed
Solve day 12
1 parent 6318271 commit 2c39724

File tree

4 files changed

+94
-0
lines changed

4 files changed

+94
-0
lines changed

2021/12/input.txt

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
xx-xh
2+
vx-qc
3+
cu-wf
4+
ny-LO
5+
cu-DR
6+
start-xx
7+
LO-vx
8+
cu-LO
9+
xx-cu
10+
cu-ny
11+
xh-start
12+
qc-DR
13+
vx-AP
14+
end-LO
15+
ny-DR
16+
vx-end
17+
DR-xx
18+
start-DR
19+
end-ny
20+
ny-xx
21+
xh-DR
22+
cu-xh

2021/12/main.hs

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import qualified Data.Set as Set
2+
import qualified Data.Graph as Graph
3+
import Data.List (sort, group)
4+
import Data.Maybe (fromJust)
5+
import Data.Tuple (swap)
6+
7+
type V = Graph.Vertex
8+
type N = String
9+
10+
parseInput = Graph.graphFromEdges
11+
. group''
12+
. sort
13+
. concat
14+
. sequence [id, map swap]
15+
. map (\x -> let (l,(_:r)) = break (=='-') x in (l, r))
16+
. lines
17+
where
18+
group' :: N -> [N] -> [(N, N)] -> [((), N, [N])]
19+
group' k v [] = [((), k, v)]
20+
group' k v ((k',v'):l) | k == k' = group' k (v':v) l
21+
| k /= k' = ((), k, v) : group' k' [v'] l
22+
group'' :: [(N, N)] -> [((), N, [N])]
23+
group'' ((k, v):l) = group' k [v] l
24+
25+
visit :: (V -> (N, [N])) -> (N -> Maybe V) -> V -> V -> V -> Bool -> Set.Set V -> [[V]]
26+
visit nfv vfk current start end twice visited
27+
= map (current:) $ foldMap (visitNode) nodes'
28+
where
29+
(curr, nodes) = nfv current
30+
nodes' = map (fromJust . vfk) nodes
31+
visitNode :: V -> [[V]]
32+
visitNode node
33+
| node == end = [[end]]
34+
| Set.member node visited && (twice' || node == start) = []
35+
| otherwise = visit nfv vfk node start end twice' insert
36+
insert | small = Set.insert current visited
37+
| otherwise = visited
38+
small = "a" <= curr && curr <= "z"
39+
twice' = twice || Set.member current visited
40+
41+
main = readFile "input.txt"
42+
>>= \x -> let (graph, nodeFromVertex, vertexFromKey) = parseInput x
43+
nfv = (\((), x, y) -> (x, y)) . nodeFromVertex
44+
vfk = vertexFromKey
45+
start = fromJust $ vfk "start"
46+
end = fromJust $ vfk "end"
47+
in print $ length
48+
$ visit nfv vfk start start end False Set.empty
49+
50+
-- Debugging functions
51+
52+
printPaths nfv = mapM_ (putStrLn . pathToString nfv)
53+
54+
pathToString nfv = tail . foldr ((++) . (',':)) "" . map f
55+
where f = (\(_, l, _) -> l) . nfv

2021/12/test.txt

+7
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

2021/12/test2.txt

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
dc-end
2+
HN-start
3+
start-kj
4+
dc-start
5+
dc-HN
6+
LN-dc
7+
HN-end
8+
kj-sa
9+
kj-HN
10+
kj-dc

0 commit comments

Comments
 (0)