Day 8: Memory maneuver - Advent of Code
Stavros Aronis
08.12.2018
I did the Advent of Code 2018 day 8 challenge in Erlang! Parts one and two are as follows:
#!/usr/bin/env escript
-mode(native).
%% https://adventofcode.com/2018/day/8
main(Args) ->
[Input] = read_input(),
Sol =
case Args of
["2"] -> value([Input], [1]);
_ -> sum_metadata([Input])
end,
io:format("~p~n", [Sol]).
read_input() ->
read_input(1).
read_input(0) -> [];
read_input(Nodes) ->
{ok, [ChildrenCount, MetaCount]} = io:fread("", "~d ~d"),
Children = read_input(ChildrenCount),
ReadMeta =
fun() ->
{ok, [M]} = io:fread("", "~d"),
M
end,
Meta = [ReadMeta() || _ <- lists:seq(1, MetaCount)],
Rest = read_input(Nodes - 1),
[{Children, Meta} | Rest].
sum_metadata([]) -> 0;
sum_metadata([{Children, Meta}|Rest]) ->
A = sum_metadata(Rest),
B = sum_metadata(Children),
C = lists:sum(Meta),
A + B + C.
value([], Meta) ->
lists:sum(Meta);
value(Children, Which) ->
Marked = select(Which, Children),
lists:sum([value(C, M) || {C, M} <- Marked]).
select(Which, Children) ->
select(Which, Children, []).
select([], _, Acc) ->
Acc;
select([N|R], Children, Acc) ->
try
C = lists:nth(N, Children),
select(R, Children, [C|Acc])
catch
_:_ ->
select(R, Children, Acc)
end.

ARTICLES: 6
Day 18: Settlers of The North Pole - Advent of Code 2018

Article by Stavros Aronis
I did the Advent of Code 2018 day 18 challenge in Erlang! Parts one and two are as follows:
READ MOREDay 14: Chocolate Charts - Advent of Code 2018

Article by Stavros Aronis
I did the Advent of Code 2018 day 14 challenge in Erlang! Parts one and two are as follows:
READ MOREDay 13: Mine Cart Madness - Advent of Code 2018

Article by Stavros Aronis
I did the Advent of Code 2018 day 13 challenge in Erlang! Parts one and two are as follows:
READ MOREDay 12: Subterranean Sustainability - Advent of Code 2018

Article by Stavros Aronis
I did the Advent of Code 2018 day 12 challenge in Erlang! Parts one and two are as follows:
READ MOREDay 9: Marble Mania - Advent of Code 2018

Article by Stavros Aronis
I did the Advent of Code 2018 day 9 challenge in Erlang! Parts one and two are as follows:
READ MORE