Skip to content

Instantly share code, notes, and snippets.

@joeytrapp
Last active December 9, 2024 06:58
Show Gist options
  • Save joeytrapp/c97b9892d36174b3a2b8322aa4c84336 to your computer and use it in GitHub Desktop.
Save joeytrapp/c97b9892d36174b3a2b8322aa4c84336 to your computer and use it in GitHub Desktop.
Advent of Code 2024 Day 2 Part 1 and Part 2
-module(aoc).
-export([main/1]).
main([Path]) ->
{ok, Data} = parse(Path),
io:format("Safe: ~p~n", [lists:sum(lists:map(fun is_safe/1, Data))]),
io:format("Dampened: ~p~n", [lists:sum(lists:map(fun is_less_safe/1, Data))]),
erlang:halt(0).
parse(Path) ->
maybe
{ok, Handle} ?= file:open(Path, [read, binary]),
{ok, Data} ?= parse(Handle, []),
ok ?= file:close(Handle),
{ok, Data}
end.
parse(IoDevice, Acc) -> parse(IoDevice, file:read_line(IoDevice), Acc).
parse(_IoDevice, eof, Acc) -> {ok, lists:reverse(Acc)};
parse(IoDevice, {ok, Data}, Acc) -> parse(IoDevice, [parse_line(Data) | Acc]).
parse_line(Line) -> parse_line(Line, <<>>, []).
parse_line(<<>>, Cur, Found) -> lists:enumerate(lists:reverse(prepend(Cur, Found)));
parse_line(<<" ", T/binary>>, Cur, Found) -> parse_line(T, <<>>, prepend(Cur, Found));
parse_line(<<C:1/binary, T/binary>>, Cur, Found) -> parse_line(T, acc(Cur, C), Found).
acc(Cur, C) when C >= <<"0">>, C =< <<"9">> -> <<Cur/binary, C/binary>>;
acc(Cur, _) -> Cur.
prepend(<<>>, Found) -> Found;
prepend(Cur, Found) -> [binary_to_integer(Cur) | Found].
is_safe([A,B|T]) when element(2,A) >= element(2,B) -> decs(A, [B|T]);
is_safe([A,B|T]) when element(2,A) < element(2,B) -> incs(A, [B|T]);
is_safe(L) when is_list(L) -> 1.
is_less_safe(L) when is_list(L) ->
case is_safe(L) of
1 -> 1;
0 -> dampen(L, L)
end.
dampen(_, []) -> 0;
dampen(L, [H|T]) ->
case is_safe(lists:delete(H, L)) of
1 -> 1;
0 -> dampen(L, T)
end.
incs(_, []) -> 1;
incs(A, [B|T]) ->
case in_range(element(2,B) - element(2,A)) of
true -> incs(B, T);
false -> 0
end.
decs(_, []) -> 1;
decs(A, [B|T]) ->
case in_range(element(2,A) - element(2,B)) of
true -> decs(B, T);
false -> 0
end.
in_range(V) -> V >= 1 andalso V =< 3.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment