-
-
Save rkallos/82d42a65d99e3db826a4193bb294e310 to your computer and use it in GitHub Desktop.
Advent of Code 2021 Day 15, solved with Erlang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env escript | |
main(Filename) -> | |
{ok, Bin} = file:read_file(Filename), | |
[InitBin | RulesLines] = binary:split(Bin, <<"\n">>, [global, trim_all]), | |
Init = binary_to_list(InitBin), | |
Rules = make_rules(RulesLines), | |
Seed = {lists:foldl(fun({C1, C2}, M) -> map_add(<<C1, C2>>, 1, M) end, #{}, | |
lists:zip(lists:droplast(Init), tl(Init))), | |
lists:foldl(fun(C, M) -> map_add(C, 1, M) end, #{}, Init)}, | |
io:format("~b~n~b~n", [solve(10, Seed, Rules), solve(40, Seed, Rules)]). | |
make_rules(Lines) -> | |
lists:foldl(fun(Line, Acc) -> | |
[From, To] = binary:split(Line, <<" -> ">>), | |
Acc#{From => To} | |
end, #{}, Lines). | |
solve(0, {_, M}, _Rules) -> lists:max(maps:values(M)) - lists:min(maps:values(M)); | |
solve(N, {Bigrams, Counts}, Rules) -> | |
F = fun(<<C1, C2>> = Bigram, Count, {Acc, CAcc}) -> | |
#{Bigram := <<CN>>} = Rules, | |
{map_add(<<CN, C2>>, Count, map_add(<<C1, CN>>, Count, Acc)), | |
map_add(CN, Count, CAcc)} | |
end, | |
solve(N - 1, maps:fold(F, {#{}, Counts}, Bigrams), Rules). | |
map_add(Key, Amt, Map) -> maps:update_with(Key, fun(V) -> V + Amt end, Amt, Map). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment