Skip to content

Instantly share code, notes, and snippets.

@ferd
Created December 10, 2021 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ferd/437f0f79fd6abea615463a842efa3369 to your computer and use it in GitHub Desktop.
Save ferd/437f0f79fd6abea615463a842efa3369 to your computer and use it in GitHub Desktop.
-module(day10).
-export([main/1]).
-mode(compile).
main([File]) ->
{ok, Bin} = file:read_file(File),
Lines = re:split(Bin, "\n", [multiline, trim, {return, list}]),
io:format("~p~n", [run(Lines)]).
run(Lines) ->
{P1, P2, _} = lists:foldl(fun run/2, {0,[],[]}, Lines),
{P1, lists:nth(trunc(length(P2)/2), lists:sort(P2))}.
run([$)|T], {P1, P2, [$(|Acc]}) -> run(T, {P1, P2, Acc});
run([$]|T], {P1, P2, [$[|Acc]}) -> run(T, {P1, P2, Acc});
run([$}|T], {P1, P2, [${|Acc]}) -> run(T, {P1, P2, Acc});
run([$>|T], {P1, P2, [$<|Acc]}) -> run(T, {P1, P2, Acc});
run([$)|_], {P1, P2, _}) -> {P1+3, P2, []};
run([$]|_], {P1, P2, _}) -> {P1+57, P2, []};
run([$}|_], {P1, P2, _}) -> {P1+1197, P2, []};
run([$>|_], {P1, P2, _}) -> {P1+25137, P2, []};
run([H|T], {P1, P2, Acc}) -> run(T, {P1, P2, [H|Acc]});
run([], {P1, P2, Acc}) ->
N = lists:foldl(fun($(,N) -> N*5+1
; ($[,N) -> N*5+2
; (${,N) -> N*5+3
; ($<,N) -> N*5+4
end, 0, Acc),
{P1, [N|P2], []}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment