commit d54e9a3faec5a5e7993a85634eb62fa4c08d4f64
parent 9e723182f09b41430bdf5ea292e86d061d2264c9
Author: Decay <decay@todayiwilllaunchmyinfantsonintoorbit.com>
Date: Sat, 10 Dec 2022 11:58:21 -0800
Day ten, Erlang
Diffstat:
A | 10/ten.erl | | | 71 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 71 insertions(+), 0 deletions(-)
diff --git a/10/ten.erl b/10/ten.erl
@@ -0,0 +1,71 @@
+-module(ten).
+
+-export([solve/0]).
+
+%% Run the solution
+solve() ->
+ {ok, In} = file:open("input", read),
+ Instructions = read_instructions(In),
+ file:close(In),
+ {_, Signal, Display} = execute(Instructions),
+ io:format("Signal strength: ~B~n", [Signal]),
+ io:format(Display).
+
+read_instructions(Dev) ->
+ read_instructions(Dev, []).
+
+read_instructions(Dev, List) ->
+ case file:read_line(Dev) of
+ {ok, Line} ->
+ read_instructions(Dev, [string:trim(Line)|List]);
+ eof ->
+ lists:reverse(List);
+ {error, badarg} ->
+ false
+ end.
+
+execute(List) ->
+ execute(List, 1, 1, 0, "").
+
+execute([], X, _, Signal, Display) ->
+ {X, Signal, Display};
+execute([Ins|Rest], X, Timer, Signal, Display) ->
+ %% io:fwrite(" Instruction: ~s, X: ~B, Timer: ~B, Signal: ~B~n", [Ins, X, Timer, Signal]),
+ [Command|Tail] = string:split(Ins, " "),
+ case Command of
+ "noop" ->
+ {NewTimer, NewSignal, NewX, NewDisplay} = timer_tick({Timer, Signal, X, Display});
+ "addx" ->
+ {NewTimer, NewSignal, TempX, NewDisplay} = timer_tick(timer_tick({Timer, Signal, X, Display})),
+ [NStr|_] = Tail,
+ {N,_} = string:to_integer(NStr),
+ NewX = TempX + N
+ end,
+ execute(Rest, NewX, NewTimer, NewSignal, NewDisplay).
+
+timer_tick({Timer, Signal, X, Display}) ->
+ Pixel = (Timer - 1) rem 40,
+ NewDisplay = draw_pixel_and_advance(Display, Pixel, X),
+ if (Timer == 20) orelse ((Timer - 20) rem 40 == 0) ->
+ %% io:fwrite("Timer: ~B, X: ~B, New Signal: ~B~n", [Timer, X, Signal + (Timer * X)]),
+ {Timer + 1, Signal + (Timer * X), X, NewDisplay};
+ true ->
+ {Timer + 1, Signal, X, NewDisplay}
+ end.
+
+draw_pixel_and_advance(Display, Pixel, Sprite) ->
+ NextPixel = next_pixel(Pixel, Sprite),
+ if (Pixel + 1) rem 40 == 0 ->
+ DispList = [Display, NextPixel, "~n"];
+ true ->
+ DispList = [Display, NextPixel]
+ end,
+ unicode:characters_to_list(DispList, unicode).
+
+next_pixel(Pixel, Sprite) ->
+ if (Pixel >= (Sprite - 1)) andalso (Pixel =< (Sprite + 1)) ->
+ "#";
+ true ->
+ "."
+ end.
+