Skip to content

Instantly share code, notes, and snippets.

@joeytrapp
Last active December 8, 2024 05:59
Show Gist options
  • Save joeytrapp/4f5d235d002299d137c5a0e420e346d7 to your computer and use it in GitHub Desktop.
Save joeytrapp/4f5d235d002299d137c5a0e420e346d7 to your computer and use it in GitHub Desktop.
Advent of Code Day 7 Part 1 and Part 2 (code only solves Part 2)
-module(aoc).
-export([main/1]).
main([Path]) ->
{ok, Content} = file:read_file(Path),
Data = parse(Content),
io:format("Result: ~p~n", [lists:sum(lists:map(fun test/1, Data))]),
erlang:halt(0).
parse(Bin) when is_binary(Bin) ->
lists:map(fun(Line) ->
[R,Rest] = binary:split(Line, <<":">>, [global, trim_all]),
I = lists:map(fun(B) ->
binary_to_integer(B)
end, binary:split(Rest, <<" ">>, [global, trim_all])),
{binary_to_integer(R), I}
end, binary:split(Bin, <<"\n">>, [global, trim_all])).
calc(add, A, B) -> A + B;
calc(mult, A, B) -> A * B;
calc(concat, A, B) ->
AB = integer_to_binary(A),
BB = integer_to_binary(B),
binary_to_integer(<<AB/binary, BB/binary>>).
build(N) -> build(N, 0, nil).
build(N, I, C) when I == N -> C;
build(N, I, C) -> build(N, I+1, expand(C)).
expand(A) when is_atom(A) -> {A,add,mult,concat};
expand({Op, nil, nil}) -> {Op,add,mult,concat};
expand({Op,N1,N2,N3}) -> {Op,expand(N1),expand(N2),expand(N3)}.
test({Result,[H|T]}) ->
case test(Result, T, build(length([H|T]) - 1), H) of
true -> Result;
false -> 0
end.
test(Result, [], _, Acc) -> Result == Acc;
test(Result, [H|T], {nil,A,B,C}, Acc) ->
test(Result, [H|T], A, Acc) orelse
test(Result, [H|T], B, Acc) orelse
test(Result, [H|T], C, Acc);
test(Result, [H|T], {Op,A,B,C}, Acc) ->
case Acc > Result of
true -> false;
false ->
test(Result, T, A, calc(Op, Acc, H)) orelse
test(Result, T, B, calc(Op, Acc, H)) orelse
test(Result, T, C, calc(Op, Acc, H))
end;
test(Result, [H|T], Op, Acc) -> test(Result, T, nil, calc(Op, Acc, H)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment