Skip to content

Instantly share code, notes, and snippets.

@ferd
Last active December 12, 2021 16:26
Show Gist options
  • Save ferd/21be3ef614a38aef8c6d3a8bd623aa03 to your computer and use it in GitHub Desktop.
Save ferd/21be3ef614a38aef8c6d3a8bd623aa03 to your computer and use it in GitHub Desktop.
-module(day12).
-export([main/1]).
-mode(compile).
main([File]) ->
{ok, Bin} = file:read_file(File),
Lines = [binary:split(Line, <<"-">>)
|| Line <- binary:split(Bin, <<"\n">>, [global, trim])],
G = lists:foldl(fun([A,B], G) -> add(A,B,add(B,A,G)) end, #{}, Lines),
io:format("part 1: ~p~npart 2: ~p~n",
[paths(G, <<"start">>, #{}, false),
paths(G, <<"start">>, #{}, true)]).
add(A,B,G) ->
maps:update_with(A, fun(Bs) -> [B|Bs] end, [B], G).
paths(_, <<"end">>, _, _) ->
1;
paths(G, <<C, _/binary>> = Node, Seen, Dup) when C >= $A, C =< $Z ->
lists:sum([paths(G, P, Seen, Dup) || P <- maps:get(Node, G)]);
paths(G, Node, Seen, Dup) when not is_map_key(Node, Seen) ->
NewSeen = Seen#{Node=>1},
lists:sum([paths(G, P, NewSeen, Dup) || P <- maps:get(Node, G)]);
paths(G, Node, Seen, true) when Node =/= <<"start">> ->
NewSeen = Seen#{Node=>1},
lists:sum([paths(G, P, NewSeen, Node) || P <- maps:get(Node, G)]);
paths(_, _, _, _) ->
0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment