Advent of Code 2021 - Day 10

This topic is about Day 10 of the Advent of Code 2021.

We have a private leaderboard (shared with users of the elixir forum ):

https://adventofcode.com/2021/leaderboard/private/view/370884

The entry code is:
370884-a6a71927

3 Likes

After day 8 everything feels easy now :slight_smile: :

main(File) ->
    {ok, RawData} = file:read_file(File),
    Data = [ binary_to_list(Line) || Line <- binary:split(RawData, <<"\n">>, [global, trim]) ],
    io:format("part 1: ~p~n", [solve1(Data)]),
    io:format("part 2: ~p~n", [solve2(Data)]).

solve1(Data) ->
    lists:sum([ score_corrupted(Char) || {corrupted, Char} <- read(Data) ]).

solve2(Data) ->
    Scores = [ score_incomplete(Chars) || {incomplete, Chars} <- read(Data) ],
    lists:nth(length(Scores) div 2 + 1, lists:sort(Scores)).

read(Data) ->
    [ read(Chars, []) || Chars <- Data ].

read([], Stack) ->
    {incomplete, Stack};
read([C|T], [C|R]) ->
    read(T, R);
read([C|T], Stack)
  when C =:= $(; C =:= $[;
       C =:= ${; C =:= $< ->
    Closing = case C of
                  $( -> $);
                  $[ -> $];
                  ${ -> $};
                  $< -> $>
              end,
    read(T, [Closing|Stack]);
read([C|_], _Stack) ->
    {corrupted, C}.

score_corrupted(C) ->
    case C of
        $) -> 3;
        $] -> 57;
        $} -> 1197;
        $> -> 25137
    end.

score_incomplete(Chars) ->
    lists:foldl(fun (C, Acc) -> 5 * Acc + score_incomplete_char(C) end, 0, Chars).

score_incomplete_char(C) ->
    case C of
        $) -> 1;
        $] -> 2;
        $} -> 3;
        $> -> 4
    end.
4 Likes

That was easy for me so it was probably very easy for you all.

4 Likes

Translated my Awk version, it handles both parts at once:

-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], []}.
5 Likes