]> fbox.kageds.com Git - adventofcode.git/blob - 2021/day17/day17.erl
day11
[adventofcode.git] / 2021 / day17 / day17.erl
1 %% to compile: erlc day3A.erl
2 %% to run: erl -noshell -s day5 solve
3 %%
4 -module(day17).
5
6 -export ([solve/0, solve/1, solve/2]).
7 -compile ([export_all]).
8
9 solve() ->
10 solve(['1']),
11 solve(['2']),
12 init:stop().
13
14 solve(A) ->
15 solve(A, read_input()).
16
17 solve(['1'], D) ->
18 io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
19 solve(1, D) ->
20 solution1(D);
21 solve(['2'], D) ->
22 io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
23 solve(2, D) ->
24 solution2(D).
25
26 solution1({X,Y}) ->
27 Xs = find_x(X),
28 Ys = find_y(Y),
29 {T, X1, Y1} = lists:max([{Key, X1, proplists:get_value(Key,Ys)} || {Key, X1} <- Xs, lists:keysearch(Key, 1, Ys) /= false]),
30 y_max(T,Y1,0).
31
32 solution2({X,Y}) ->
33 Xs = find_x(X),
34 Ys = find_y(Y),
35 length(lists:usort([{X,Y} || {Ty, Y} <- Ys, {T,X} <- lists:filter(fun({T,X}) -> T == Ty end, Xs)])).
36
37 read_input() ->
38 {{124,174},{-123, -86}}.
39 %% {{20,30},{-10, -5}}.
40
41 find_x({Xmin, Xmax}) ->
42 [ {T, Xstart} || Xstart <- lists:seq(0,400), T <- lists:seq(1,1000), x(Xstart, T) >= Xmin, x(Xstart, T) =< Xmax ].
43
44 find_y({Ymin, Ymax}) ->
45 [ {T, Ystart} || Ystart <- lists:seq(-400,400), T <- lists:seq(1,1000), y(Ystart, T) >= Ymin, y(Ystart, T) =< Ymax ].
46
47 x(Xstart, T) ->
48 Last =
49 case (Xstart - T + 1) of
50 L when L < 0 -> 0;
51 L -> L
52 end,
53 (Xstart - Last + 1) * (Xstart + Last) div 2.
54
55 y(Ystart, T) ->
56 Last = (Ystart - T + 1),
57 (Ystart - Last + 1) * (Ystart + Last) div 2.
58
59 y_max(0, _, Ymax) -> Ymax;
60 y_max(T, Y, Ymax) ->
61 NewY = y(Y, T),
62 NewMax =
63 case NewY of
64 M when M > Ymax -> M;
65 _ -> Ymax
66 end,
67 y_max(T-1, Y, NewMax).
68