1 %% to compile: erlc day3A.erl
2 %% to run: erl -noshell -s day5 solve
6 -export ([solve/0, solve/1, solve/2]).
7 -export ([read_input/0]).
15 solve(A, read_input()).
18 io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
22 io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
27 {ok, IO} = file:open("input.txt", 'read'),
28 Data = read_input(IO),
35 read_input(IO, Input) ->
38 Line -> read_input(IO, Input ++ [Line])
42 case file:read_line(IO) of
44 {ok, Line} -> parse_line(Line)
48 [Cave1, Cave2] = string:tokens(Line, "-\n"),
52 CaveMap = insert(Caves),
53 count_paths("start", #{}, 'some', CaveMap).
56 CaveMap = insert(Caves),
57 count_paths("start", #{}, 'none', CaveMap).
60 insert(Caves) -> insert(Caves, maps:new()).
62 insert([], CaveMap) -> CaveMap;
63 insert([{Cave1, Cave2}|Rest], CaveMap) ->
65 case maps:is_key(Cave1, CaveMap) of
66 'false' -> maps:put(Cave1, [Cave2], CaveMap);
67 'true' -> maps:put(Cave1, [Cave2|maps:get(Cave1, CaveMap)], CaveMap)
70 case maps:is_key(Cave2, NewMap) of
71 'false' -> maps:put(Cave2, [Cave1], NewMap);
72 'true' -> maps:put(Cave2, [Cave1|maps:get(Cave2, CaveMap)], NewMap)
74 insert(Rest, NewMap2).
76 visit_vertex(Name, Visited, VisitedTwice, Graph) ->
78 case hd(Name) >= $a of
79 true -> Visited#{Name => true};
82 #{Name := Neighbours} = Graph,
83 lists:sum([count_paths(N, NewVisited, VisitedTwice, Graph) || N <- Neighbours]).
85 count_paths("end", _, _, _) ->
86 % We have found an entire path through the graph.
88 count_paths("start", Visited, _, _) when map_size(Visited) > 0 ->
89 % We cannot visit the start cave more than once.
91 count_paths(Name, Visited, VisitedTwice, Graph) when hd(Name) >= $a andalso is_map_key(Name, Visited) ->
92 % We can visit only one small cave twice.
94 'none' -> visit_vertex(Name, Visited, Name, Graph);
97 count_paths(Name, Visited, VisitedTwice, Graph) ->
98 % Small caves can only be visited once, but large caves may be visited any
100 visit_vertex(Name, Visited, VisitedTwice, Graph).