Compare commits

...

10 Commits

Author SHA1 Message Date
34e8893d31 day06 2023-12-06 13:17:46 +00:00
52105f4958 day05 2023-12-05 21:20:05 +00:00
56571eadf0 day3 and 4 2023-12-04 13:31:13 +00:00
e7cd9346f2 day02 2023-12-01 09:12:24 +00:00
87786ac5b1 20223 day1 2023-12-01 01:41:29 +00:00
Gareth Evans
2843713a0b Day_1 2023-12-01 10:12:50 +00:00
8d5196a10f day11 2023-11-27 14:38:53 +00:00
f133e157a1 re-organise repo 2023-11-16 10:48:53 +00:00
f62c52d8a9 commit 2022-10-04 11:32:17 +00:00
6110e75650 commit 2022-10-03 10:30:54 +00:00
131 changed files with 19172 additions and 15 deletions

144
2021/day11/day11.erl Normal file
View File

@@ -0,0 +1,144 @@
%% to compile: erlc day3A.erl
%% to run: erl -noshell -s day3 solve
%%
-module(day11).
-export ([solve/0, solve/1, solve/2]).
-export ([read_input/0]).
-compile([export_all]).
solve() ->
solve(['1']),
solve(['2']),
init:stop().
solve(A) ->
solve(A, read_input()).
solve(['1'], D) ->
io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
solve(1, D) ->
solution1(D);
solve(['2'], D) ->
io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
solve(2, D) ->
solution2(D).
read_input() ->
{ok, IO} = file:open("input.txt", 'read'),
Data = read_input(IO),
file:close(IO),
Data.
read_input(IO) ->
read_input(IO, []).
read_input(IO, Input) ->
case read_line(IO) of
'eof' -> Input;
Line -> read_input(IO, Input ++ [Line])
end.
read_line(IO) ->
case file:read_line(IO) of
'eof' -> 'eof';
{ok, Line} -> [ X - $0 || X <- Line, [X] /= "\n"]
end.
solution1(Input) ->
Coords = coords(Input),
Data = [ {X, init_data(X, Input)} || X <- Coords],
put(flash, 0),
sn1_step(Data, 0),
get(flash).
sn1_step(Data, 100) -> Data;
sn1_step(Data, Count) ->
Step1 = step1(Data),
Step2 = step2(Step1),
sn1_step(Step2, Count + 1).
solution2(Input) ->
Coords = coords(Input),
Data = [ {X, init_data(X, Input)} || X <- Coords],
put(flash, 0),
sn2_step(Data, 0).
sn2_step(Data, Count) ->
Step1 = step1(Data),
Step2 = step2(Step1),
case all_flash(Step2) of
'true'-> Count + 1;
'false' -> sn2_step(Step2, Count + 1)
end.
all_flash(Data) ->
lists:all(fun({_,V}) -> V == 0 end, Data).
coords([H|_] = Table) ->
X = length(H),
Y = length(Table),
lists:flatten([[{A,B} || A <- lists:seq(1,X)] || B <- lists:seq(1,Y)]).
step1(Data) ->
lists:map(fun({C, X}) -> case X of 9 -> incr_flash(), {C, 'flash'}; _ -> {C, X + 1} end end, Data).
step2(Data) ->
case is_flash(Data) of
'true' -> flash(Data);
'false' -> clear_flashed(Data)
end.
is_flash(Data) ->
lists:any(fun({_, X}) -> X == 'flash' end, Data).
flash(Data) ->
NewData = flash(Data, Data),
step2(flashed(Data, NewData)).
flash([], Acc) -> Acc;
flash([{{X,Y},V}|T], Acc) when V == 'flash' ->
flash(T, increase_neighbors({X,Y}, Acc));
flash([_|T], Acc) -> flash(T, Acc).
clear_flashed(Data) ->
clear_flashed(Data, []).
clear_flashed([], Acc) -> lists:reverse(Acc);
clear_flashed([{C, V}|T], Acc) when V == 'flashed' ->
clear_flashed(T, [{C, 0}|Acc]);
clear_flashed([H|T], Acc) ->
clear_flashed(T, [H|Acc]).
flashed(OldData, NewData) ->
lists:zipwith(fun({C, V}, N) -> case V of 'flash' -> {C, 'flashed'}; _ -> N end end, OldData, NewData).
increase_neighbors({X,Y}, Data) ->
Neigbours = [{X+1,Y},{X-1,Y},{X,Y+1},{X,Y-1},{X+1,Y+1},{X+1,Y-1},{X-1,Y+1},{X-1,Y-1}],
increase_neighbor(Neigbours, Data).
increase_neighbor([], Data) -> Data;
increase_neighbor([{X,Y}|T], Data) when X < 1; Y < 1; X > 10; Y > 10 -> io:format("ignore: ~p~n",[{X,Y}]), increase_neighbor(T,Data);
increase_neighbor([H|T], Data) ->
case get_value(H, Data) of
'flash' -> increase_neighbor(T, Data);
'flashed' -> increase_neighbor(T, Data);
9 -> incr_flash(), increase_neighbor(T, set_value(H, Data, 'flash'));
V -> increase_neighbor(T, set_value(H, Data, V + 1))
end.
get_value(C, Table) ->
{C, V} = lists:keyfind(C, 1, Table),
V.
set_value(C, Table, V) ->
lists:keyreplace(C, 1, Table, {C, V}).
init_data({X,Y}, Table) ->
lists:nth(X, lists:nth(Y, Table)).
incr_flash() ->
put(flash, get(flash) + 1).

10
2021/day11/input.txt Normal file
View File

@@ -0,0 +1,10 @@
6617113584
6544218638
5457331488
1135675587
1221353216
1811124378
1387864368
4427637262
6778645486
3682146745

100
2021/day12/day12.erl Normal file
View File

@@ -0,0 +1,100 @@
%% to compile: erlc day3A.erl
%% to run: erl -noshell -s day5 solve
%%
-module(day12).
-export ([solve/0, solve/1, solve/2]).
-export ([read_input/0]).
solve() ->
solve(['1']),
solve(['2']),
init:stop().
solve(A) ->
solve(A, read_input()).
solve(['1'], D) ->
io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
solve(1, D) ->
solution1(D);
solve(['2'], D) ->
io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
solve(2, D) ->
solution2(D).
read_input() ->
{ok, IO} = file:open("input.txt", 'read'),
Data = read_input(IO),
file:close(IO),
Data.
read_input(IO) ->
read_input(IO, []).
read_input(IO, Input) ->
case read_line(IO) of
'eof' -> Input;
Line -> read_input(IO, Input ++ [Line])
end.
read_line(IO) ->
case file:read_line(IO) of
'eof' -> 'eof';
{ok, Line} -> parse_line(Line)
end.
parse_line(Line) ->
[Cave1, Cave2] = string:tokens(Line, "-\n"),
{Cave1, Cave2}.
solution1(Caves) ->
CaveMap = insert(Caves),
count_paths("start", #{}, 'some', CaveMap).
solution2(Caves) ->
CaveMap = insert(Caves),
count_paths("start", #{}, 'none', CaveMap).
insert(Caves) -> insert(Caves, maps:new()).
insert([], CaveMap) -> CaveMap;
insert([{Cave1, Cave2}|Rest], CaveMap) ->
NewMap =
case maps:is_key(Cave1, CaveMap) of
'false' -> maps:put(Cave1, [Cave2], CaveMap);
'true' -> maps:put(Cave1, [Cave2|maps:get(Cave1, CaveMap)], CaveMap)
end,
NewMap2 =
case maps:is_key(Cave2, NewMap) of
'false' -> maps:put(Cave2, [Cave1], NewMap);
'true' -> maps:put(Cave2, [Cave1|maps:get(Cave2, CaveMap)], NewMap)
end,
insert(Rest, NewMap2).
visit_vertex(Name, Visited, VisitedTwice, Graph) ->
NewVisited =
case hd(Name) >= $a of
true -> Visited#{Name => true};
false -> Visited
end,
#{Name := Neighbours} = Graph,
lists:sum([count_paths(N, NewVisited, VisitedTwice, Graph) || N <- Neighbours]).
count_paths("end", _, _, _) ->
% We have found an entire path through the graph.
1;
count_paths("start", Visited, _, _) when map_size(Visited) > 0 ->
% We cannot visit the start cave more than once.
0;
count_paths(Name, Visited, VisitedTwice, Graph) when hd(Name) >= $a andalso is_map_key(Name, Visited) ->
% We can visit only one small cave twice.
case VisitedTwice of
'none' -> visit_vertex(Name, Visited, Name, Graph);
_ -> 0
end;
count_paths(Name, Visited, VisitedTwice, Graph) ->
% Small caves can only be visited once, but large caves may be visited any
% number of times.
visit_vertex(Name, Visited, VisitedTwice, Graph).

21
2021/day12/input.txt Normal file
View File

@@ -0,0 +1,21 @@
TR-start
xx-JT
xx-TR
hc-dd
ab-JT
hc-end
dd-JT
ab-dd
TR-ab
vh-xx
hc-JT
TR-vh
xx-start
hc-ME
vh-dd
JT-bm
end-ab
dd-xx
end-TR
hc-TR
start-vh

12
2021/day13/commmands.txt Normal file
View File

@@ -0,0 +1,12 @@
fold along x=655
fold along y=447
fold along x=327
fold along y=223
fold along x=163
fold along y=111
fold along x=81
fold along y=55
fold along x=40
fold along y=27
fold along y=13
fold along y=6

88
2021/day13/day13.erl Normal file
View File

@@ -0,0 +1,88 @@
%% to compile: erlc day3A.erl
%% to run: erl -noshell -s day5 solve
%%
-module(day13).
-export ([solve/0, solve/1, solve/2]).
-export ([read_input/0]).
solve() ->
solve(['1']),
solve(['2']),
init:stop().
solve(A) ->
solve(A, read_input()).
solve(['1'], D) ->
io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
solve(1, D) ->
solution1(D);
solve(['2'], D) ->
io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
solve(2, D) ->
solution2(D).
read_input() ->
{ok, IO} = file:open("input.txt", 'read'),
Data = read_input(IO),
file:close(IO),
Data.
read_input(IO) ->
read_input(IO, []).
read_input(IO, Input) ->
case read_line(IO) of
'eof' -> Input;
Line -> read_input(IO, Input ++ [Line])
end.
read_line(IO) ->
case file:read_line(IO) of
'eof' -> 'eof';
{ok, Line} -> parse_line(Line)
end.
parse_line(Line) ->
Points = string:tokens(Line, " ,\n"),
[X, Y] = [list_to_integer(X) || X <- Points],
{X, Y}.
solution1(Input) ->
io:format("Input ~p~n", [Input]),
F1 = fold(x, 655, Input),
length(F1).
solution2(Input) ->
I = fold(y,6,fold(y,13,fold(y,27,fold(x,40,fold(y,55,fold(x,81,fold(y,111,fold(x,163,fold(y,223,fold(x,327,fold(y,447,fold(x,655, Input)))))))))))),
MaxX = lists:foldl(fun({T, _}, Acc) -> case T > Acc of 'true' -> T; _ -> Acc end end, 0, I),
MaxY = lists:foldl(fun({_, T}, Acc) -> case T > Acc of 'true' -> T; _ -> Acc end end, 0, I),
Coords = [{X,Y} || Y <- lists:seq(0,MaxY), X <- lists:seq(0,MaxX)],
output(Coords, I, MaxX).
output([], I, MaxX) -> ok;
output([{X,Y}|Rest], I, MaxX) ->
case lists:member({X,Y}, I) of
'true' -> io:format("#");
'false' -> io:format(" ")
end,
case X == MaxX of
'true' -> io:format("~n");
'false' -> ok
end,
output(Rest, I, MaxX).
fold(y, N, Input) ->
L1 = [ {X, (Y * -1) + N} || {X, Y} <- Input],
{Sat, NotSat} = lists:partition(fun({_,Y}) -> Y < 0 end, L1),
Sat2 = [{X, Y * -1}|| {X, Y} <- Sat],
L2 = lists:usort(NotSat ++ Sat2),
[ {X, (Y - N) * -1} || {X,Y} <- L2];
fold(x, N, Input) ->
L1 = [ {(X * -1) + N, Y} || {X, Y} <- Input],
{Sat, NotSat} = lists:partition(fun({X,_}) -> X < 0 end, L1),
Sat2 = [{X * -1, Y}|| {X, Y} <- Sat],
L2 = lists:usort(NotSat ++ Sat2),
[ {(X - N) * -1, Y} || {X,Y} <- L2].

907
2021/day13/input.txt Normal file
View File

@@ -0,0 +1,907 @@
949,224
398,211
402,700
900,890
1197,304
333,809
681,705
769,864
975,465
639,523
445,313
912,99
502,894
703,343
572,598
1232,759
277,640
700,761
919,429
678,141
1054,795
934,750
760,73
268,627
336,859
1096,135
646,176
55,404
932,872
1168,338
569,842
904,863
647,168
509,606
42,525
607,343
947,861
1002,537
1230,368
186,274
363,690
1073,663
868,312
646,718
385,210
961,660
1277,0
470,228
127,705
894,89
500,704
994,361
87,582
985,378
557,607
75,872
1068,647
686,138
358,84
957,415
325,516
711,169
1287,252
619,242
329,516
821,714
514,844
632,358
549,252
442,302
619,652
5,809
276,530
15,75
653,266
632,536
731,648
237,231
1266,19
966,205
360,37
522,3
1255,725
833,840
898,728
805,162
294,261
1250,833
403,151
1288,564
7,465
350,274
1133,478
408,526
1079,493
310,205
420,507
1310,596
639,824
328,257
30,417
845,511
196,683
1002,201
719,96
15,457
276,812
760,43
979,95
319,429
661,429
654,298
584,421
372,355
351,252
430,453
113,304
701,772
107,628
549,700
629,551
492,851
427,101
278,666
246,856
194,82
417,439
433,712
425,229
308,89
1275,652
1193,316
482,190
955,245
465,511
688,37
788,525
92,235
644,417
1247,877
25,327
1255,404
502,0
960,760
431,570
741,702
728,606
1086,453
1198,694
181,208
401,327
959,194
729,863
1295,819
7,271
263,456
132,868
318,849
242,726
1133,392
631,294
410,302
654,582
649,465
622,709
805,284
1300,533
731,22
579,470
177,392
1079,849
252,397
898,871
634,618
427,653
433,630
1228,851
686,865
1079,32
105,252
372,761
15,864
644,222
1134,122
572,851
1303,429
991,726
304,620
962,446
899,586
667,44
786,228
719,93
411,742
1031,110
33,0
646,483
482,288
885,47
1250,609
632,330
594,833
1178,868
68,542
482,480
818,851
278,592
898,726
141,660
360,857
515,651
30,532
865,540
1168,500
1022,525
80,526
975,429
401,159
1256,523
1300,809
410,598
537,540
482,606
25,551
229,709
1096,555
952,756
23,70
584,38
810,288
495,416
278,358
900,43
550,43
895,582
1221,213
1205,252
1180,732
524,3
850,641
1054,421
865,581
376,37
751,233
72,64
969,717
1032,666
1170,50
112,200
279,784
818,43
810,704
972,222
738,296
1285,791
162,403
333,85
1168,786
1161,51
840,498
3,351
966,644
522,891
666,222
751,592
842,50
480,446
885,847
7,623
137,638
1208,703
668,716
477,416
1307,351
981,555
117,578
430,254
1280,417
428,809
743,312
634,620
1225,724
10,869
631,700
87,312
1237,689
388,285
358,810
1111,894
1133,499
113,752
666,670
1198,200
196,451
1079,302
1098,521
987,95
1295,523
1275,591
1131,855
440,583
1171,691
955,201
112,135
291,861
50,588
1032,358
678,330
689,446
30,815
411,152
505,610
251,246
1052,430
427,793
1173,383
1143,431
607,791
189,32
1057,7
1307,543
1173,374
430,677
313,289
624,756
1048,429
1205,70
231,862
947,690
966,250
1220,851
1253,210
269,427
850,701
1034,812
748,211
868,73
279,110
664,624
971,506
1009,327
214,555
80,632
1136,648
1133,854
557,5
997,605
1079,45
174,648
159,351
341,717
934,218
549,194
1079,862
774,467
423,177
1126,50
1039,255
154,717
1256,75
1006,620
1136,757
73,831
65,441
95,415
0,596
455,33
460,641
528,427
15,437
627,201
142,786
714,386
922,144
97,606
455,57
1084,309
840,725
840,396
428,533
679,600
607,103
965,662
674,542
199,894
691,425
728,382
636,352
251,85
149,527
181,686
253,119
1124,172
1059,757
25,383
15,371
540,347
793,638
1305,809
1221,231
681,479
870,107
818,512
427,457
174,757
559,233
1263,343
11,626
174,246
44,875
211,453
1000,250
160,714
802,698
181,9
883,101
994,415
1262,106
715,548
934,228
378,82
262,429
23,252
495,351
885,665
656,582
1111,837
609,324
704,788
994,733
348,620
877,642
971,850
1242,430
513,234
341,157
221,476
443,441
159,767
907,295
1287,824
622,485
1297,659
863,455
1266,133
596,386
1042,85
566,805
711,404
1019,204
904,479
1310,760
1164,877
1054,235
986,392
952,84
468,50
231,302
1159,716
979,799
1178,815
686,29
336,35
796,844
1059,375
445,130
644,533
865,537
542,86
1130,129
1196,750
162,627
95,849
339,492
1173,256
489,597
972,415
877,630
885,717
726,38
1288,834
934,302
870,364
711,649
773,130
410,43
1133,395
1091,714
900,296
258,240
1144,852
982,596
1129,885
960,386
786,443
378,872
1130,765
348,274
1230,526
415,312
729,31
1180,162
793,704
448,525
149,630
816,180
555,121
974,45
1143,687
214,87
48,788
499,367
412,728
796,396
1260,812
679,376
65,383
591,96
512,52
420,828
589,889
435,649
149,591
1114,666
231,849
1151,351
64,205
1240,856
970,436
145,457
579,648
50,193
1168,108
22,834
885,495
1218,235
70,347
1293,353
632,834
278,857
1213,453
971,268
514,396
957,479
619,649
490,736
1302,849
1086,640
890,380
619,591
671,70
159,655
10,421
862,369
441,192
818,64
1183,705
679,824
1196,185
114,302
633,660
1228,40
435,245
256,235
651,351
410,296
947,21
992,859
89,213
482,177
112,459
999,630
774,203
763,628
985,516
1261,640
828,187
562,211
923,10
87,309
1146,736
512,500
305,234
1295,371
647,271
1096,584
508,353
1297,812
972,448
688,485
1081,512
104,403
401,703
1073,231
311,883
833,812
1032,857
239,582
503,716
343,152
664,176
1168,672
167,207
401,775
1116,474
398,683
331,799
952,532
1228,647
1287,600
908,642
402,642
355,245
335,465
788,891
678,536
8,493
318,859
1235,872
177,873
748,659
242,168
796,641
440,331
162,491
1171,203
477,840
350,162
524,666
591,877
22,330
962,274
629,567
977,809
828,480
291,413
1211,569
1193,764
468,274
805,591
395,45
589,511
1299,388
883,437
1302,483
1097,702
868,821
423,401
972,446
30,79
376,218
899,742
339,44
721,63
67,54
795,651
353,415
805,723
246,247
261,5
1047,456
706,82
344,644
1170,760
984,596
493,297
253,735
349,234
155,840
349,660
736,695
994,670
199,837
221,712
423,65
1083,101
386,732
346,245
1133,873
1121,63
1255,714
880,441
514,641
1299,836
1108,33
1278,400
241,500
788,79
1056,569
810,190
584,856
1043,548
1285,103
1288,249
1004,274
1034,530
244,890
1192,691
401,31
155,591
72,736
351,642
487,416
934,37
319,255
1136,137
442,73
169,170
1295,75
862,525
388,526
831,58
1119,649
411,84
902,247
253,7
840,617
1000,196
821,138
1000,205
710,819
13,235
914,654
1161,527
1262,261
492,830
455,705
622,185
1047,793
140,760
1275,649
316,733
345,662
267,884
1141,618
1299,58
440,107
991,175
852,451
23,824
375,110
468,172
541,590
1001,801
773,481
442,373
788,369
500,288
960,610
894,252
224,631
1111,189
1059,533
1029,716
114,709
768,883
541,752
1076,514
1277,894
1133,306
202,861
798,52
845,383
647,726
833,416
584,473
841,234
1245,5
30,756
818,267
885,512
572,488
417,614
1155,840
774,691
149,51
786,732
10,701
689,33
440,364
681,63
643,44
294,633
786,666
411,586
256,795
793,714
32,494
768,135
378,530
196,228
164,736
822,490
495,767
105,264
1073,679
445,242
719,877
146,698
1262,358
736,526
1237,831
965,93
177,588
877,712
75,22
887,65
915,849
1016,261
22,141
227,457
540,99
8,411
701,570
629,343
261,453
154,707
117,255
72,830
691,652
751,302
447,455
890,507
209,354
1238,736
338,448
574,526
1000,698
324,502
1066,4
44,19
632,60
768,459
25,567
1034,364
949,670
231,829
924,610
166,42
703,103
738,851
212,521
898,168
664,718
683,201
358,756
45,527
1235,22
666,533
686,756
132,369
1252,715
1016,270
828,288
226,309
358,138
1066,247
960,162
517,399
401,607
301,327
8,483
482,704
882,585
744,805
406,863
1148,627
44,133
1253,684
1129,9
1193,191
815,351
738,406
388,592
515,243
155,303
447,439
917,677
1041,609
10,361
137,383
858,861
1012,441
1173,404
1041,427
137,520
442,750
166,852
147,263
835,396
912,211
209,481
879,570
959,600
495,655
1119,21
253,241
631,642
492,512
719,798
344,205
599,245
997,289
703,791
1124,274
1071,582
909,607

168
2021/day14/day14.erl Normal file
View File

@@ -0,0 +1,168 @@
%% to compile: erlc day3A.erl
%% to run: erl -noshell -s day5 solve
%%
-module(day14).
-export ([solve/0, solve/1, solve/2]).
-export ([expand_pair/4, read_input/0]).
-compile ([export_all]).
solve() ->
solve(['1']),
solve(['2']),
init:stop().
solve(A) ->
solve(A, read_input()).
solve(['1'], D) ->
io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
solve(1, D) ->
solution1(D);
solve(['2'], D) ->
io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
solve(2, D) ->
solution2(D).
read_input() ->
{ok, IO} = file:open("input.txt", 'read'),
Data = read_input(IO),
file:close(IO),
Data.
read_input(IO) ->
read_input(IO, []).
read_input(IO, Input) ->
case read_line(IO) of
'eof' -> make_map(Input);
Line -> read_input(IO, Input ++ [Line])
end.
read_line(IO) ->
case file:read_line(IO) of
'eof' -> 'eof';
{ok, Line} -> parse_line(Line)
end.
parse_line(Line) ->
string:tokens(Line, " ->\n").
make_map(Input) -> make_map(Input, maps:new()).
make_map([], Map) -> Map;
make_map([[P, [Res]]|Rest], Map) ->
NewMap = maps:put(P, Res, Map),
make_map(Rest, NewMap).
solution1(PolyMap) ->
Ets = ets:new(polymer, [set, public, named_table]),
Polymer = "FNFPPNKPPHSOKFFHOFOC",
init_counters(Ets, PolyMap),
io:format("~p~n", [ets:tab2list(Ets)]),
Pairs = make_pairs(Polymer, []),
io:format("expand pairs: ~p~n",[Pairs]),
count_pairs(Pairs, Ets),
[count_elems(Pair, Ets, 1) || Pair <- Pairs],
loop(Ets, PolyMap, 10),
get_max_elm(Ets) - get_min_elm(Ets).
solution2(PolyMap) ->
Ets = ets:new(polymer, [set, public, named_table]),
Polymer = "FNFPPNKPPHSOKFFHOFOC",
init_counters(Ets, PolyMap),
io:format("~p~n", [ets:tab2list(Ets)]),
Pairs = make_pairs(Polymer, []),
io:format("expand pairs: ~p~n",[Pairs]),
count_pairs(Pairs, Ets),
[count_elems(Pair, Ets, 1) || Pair <- Pairs],
loop(Ets, PolyMap, 40),
get_max_elm(Ets) - get_min_elm(Ets).
get_max_elm(Ets) ->
Ents = ets:tab2list(Ets),
{V, _} = lists:max([{V,X} || {{elem, X},V} <- Ents]),
V.
get_min_elm(Ets) ->
Ents = ets:tab2list(Ets),
{V, _} = lists:min([{V,X} || {{elem, X},V} <- Ents]),
V.
loop(Ets, _PolyMap, 0) -> ets:tab2list(Ets);
loop(Ets, PolyMap, Count) ->
Counters = get_counters(Ets),
[update_ets(Ets, PolyMap, Counter) || Counter <- Counters],
loop(Ets, PolyMap, Count - 1).
init_counters(Ets, PolyMap) ->
maps:foreach(fun([X,Y] = Key, _Value) -> ets:insert(Ets, {{elem,X},0}), ets:insert(Ets, {{elem,Y},0}), ets:insert(Ets, {{pair, Key}, 0}) end, PolyMap).
update_ets(_Ets, _PolyMap, {_Key, 0}) -> ok;
update_ets(Ets, PolyMap, {[X,Y] = Key, Value}) ->
V = maps:get(Key, PolyMap),
count_pair([X,V],Ets, Value),
count_pair([V,Y],Ets, Value),
count_pair(Key,Ets, -1 * Value),
count_elem(V, Ets, Value).
get_counters(Ets) ->
Ents = ets:tab2list(Ets),
[{X,V} || {{pair, X},V} <- Ents].
make_pairs([_], Pairs) -> Pairs;
make_pairs([X,Y|Rest], Pairs) -> make_pairs([Y|Rest], [[X,Y]|Pairs]).
count_pairs([], _Ets) -> ok;
count_pairs([P|Rest], Ets) ->
count_pair(P, Ets, 1),
count_pairs(Rest, Ets).
count_pair(P, Ets, V) ->
ets:update_counter(Ets, {pair,P}, {2,V}).
count_elems([X,Y], Ets, V) ->
count_elem(X, Ets, V),
count_elem(Y, Ets, V).
count_elem(Elem, Ets, V) ->
ets:update_counter(Ets, {elem,Elem}, {2,V}).
expand_pair(_P, _PolyMap, _Ets, 0) -> ok;
expand_pair([P1,P2], PolyMap, Ets, Count) when is_list(P1), is_list(P2) ->
expand_pair(P1,PolyMap, Ets, Count - 1);
expand_pair([X,Y] = P, PolyMap, Ets, Count) ->
[V] = maps:get(P, PolyMap),
ets:update_counter(Ets, [V], {2,1}),
[expand_pair(Pa, PolyMap, Ets, Count) || Pa <- [[X,V]] ++ [[V,Y]]].
pairs([], _PolyMap, Pairs, _Ets, 0) ->
Pairs;
pairs([], PolyMap, Pairs, Ets, Count) ->
io:format("new pairs: ~p~n", [Pairs]),
pairs(Pairs, PolyMap, [], Ets, Count - 1);
pairs([[X,Y] = P|Rest], PolyMap, Pairs, Ets, Count) ->
[V] = maps:get(P, PolyMap),
ets:update_counter(Ets, [V], {2,1}),
pairs(Rest, PolyMap, Pairs ++ [[X,V]] ++ [[V,Y]], Ets, Count).
count(Polymer) ->
Ps = lists:usort(Polymer),
[ {count_p(P, Polymer), [P]} || P <- Ps].
count_p(P, Polymer) ->
lists:foldl(fun(X, Acc) -> case X == P of 'true' -> Acc + 1; _ -> Acc end end, 0, Polymer).
steps(Polymer, _PolyMap, 0) -> Polymer;
steps(Polymer, PolyMap, Count) ->
Insert = get_insert_list(Polymer, PolyMap),
steps(lists:flatten(lists:zipwith(fun(A, B) -> [A,B] end, Polymer, Insert)), PolyMap, Count - 1).
get_insert_list(Polymer, PolyMap) ->
get_insert_list(Polymer, PolyMap, []).
get_insert_list([_], _PolyMap, InsertList) -> lists:reverse([[]|InsertList]);
get_insert_list([P1,P2|Rest], PolyMap, InsertList) ->
V = maps:get([P1,P2], PolyMap),
get_insert_list([P2|Rest], PolyMap, [V|InsertList]).

100
2021/day14/input.txt Normal file
View File

@@ -0,0 +1,100 @@
VS -> B
SV -> C
PP -> N
NS -> N
BC -> N
PB -> F
BK -> P
NV -> V
KF -> C
KS -> C
PV -> N
NF -> S
PK -> F
SC -> F
KN -> K
PN -> K
OH -> F
PS -> P
FN -> O
OP -> B
FO -> C
HS -> F
VO -> C
OS -> B
PF -> V
SB -> V
KO -> O
SK -> N
KB -> F
KH -> C
CC -> B
CS -> C
OF -> C
FS -> B
FP -> H
VN -> O
NB -> N
BS -> H
PC -> H
OO -> F
BF -> O
HC -> P
BH -> S
NP -> P
FB -> C
CB -> H
BO -> C
NN -> V
SF -> N
FC -> F
KK -> C
CN -> N
BV -> F
FK -> C
CF -> F
VV -> B
VF -> S
CK -> C
OV -> P
NC -> N
SS -> F
NK -> V
HN -> O
ON -> P
FH -> O
OB -> H
SH -> H
NH -> V
FF -> B
HP -> B
PO -> P
HB -> H
CH -> N
SN -> P
HK -> P
FV -> H
SO -> O
VH -> V
BP -> V
CV -> P
KP -> K
VB -> N
HV -> K
SP -> N
HO -> P
CP -> H
VC -> N
CO -> S
BN -> H
NO -> B
HF -> O
VP -> K
KV -> H
KC -> F
HH -> C
BB -> K
VK -> P
OK -> C
OC -> C
PH -> H

166
2021/day15/day15.erl Normal file
View File

@@ -0,0 +1,166 @@
%% to compile: erlc day3A.erl
%% to run: erl -noshell -s day3 solve
%%
-module(day15).
-export ([solve/0, solve/1, solve/2]).
-export ([read_input/0]).
-compile([export_all]).
solve() ->
solve(['1']),
solve(['2']),
init:stop().
solve(A) ->
solve(A, read_input()).
solve(['1'], D) ->
io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
solve(1, D) ->
solution1(D);
solve(['2'], D) ->
io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
solve(2, D) ->
solution2(D).
read_input() ->
{ok, IO} = file:open("input.txt", 'read'),
Data = read_input(IO),
file:close(IO),
Data.
read_input(IO) ->
read_input(IO, []).
read_input(IO, Input) ->
case read_line(IO) of
'eof' -> Input;
Line -> read_input(IO, Input ++ [Line])
end.
read_line(IO) ->
case file:read_line(IO) of
'eof' -> 'eof';
{ok, Line} -> [ X - $0 || X <- Line, [X] /= "\n"]
end.
solution1(Input) ->
Graph = astar:graph(Input),
astar:search(Graph, {0, 0}, {99, 99}).
solution2(Input) ->
Graph = astar:graph(Input),
astar:search(Graph, {0, 0}, {499, 499}).
coords([H|_] = Table) ->
X = length(H),
Y = length(Table),
lists:flatten([[{A,B} || A <- lists:seq(1,X)] || B <- lists:seq(1,Y)]).
%init_data({X,Y}, Table) when X =< 100 andalso Y =< 100 ->
% lists:nth(X, lists:nth(Y, Table));
init_data({X,Y}, Table) ->
X1 =
case (X rem 100) of
0 -> 100;
A -> A
end,
Y1 =
case (Y rem 100) of
0 -> 100;
B -> B
end,
D = lists:nth(X1, lists:nth(Y1, Table)),
D1 = (D + ((X-1) div 100) + ((Y-1) div 100)) rem 9,
D2 =
case D1 of
0 -> 9;
C -> C
end,
%% io:format("~p -> ~p -> ~p~n", [{X,Y},{X1,Y1},{D,D2}]),
D2.
get_value({X,Y}, _Table) when X < 1; Y < 1; X > 500; Y > 500 -> 'invalid';
get_value({X,Y}, Table) ->
%% {C, V} = lists:keyfind(C, 1, Data),
%% V.
X1 =
case (X rem 100) of
0 -> 100;
A -> A
end,
Y1 =
case (Y rem 100) of
0 -> 100;
B -> B
end,
D = lists:nth(X1, lists:nth(Y1, Table)),
D1 = (D + ((X-1) div 100) + ((Y-1) div 100)) rem 9,
D2 =
case D1 of
0 -> 9;
C -> C
end,
%% io:format("~p -> ~p -> ~p~n", [{X,Y},{X1,Y1},{D,D2}]),
D2.
get_neighbors({X,Y}, Data) ->
Neigbours = [{X+1,Y},{X-1,Y},{X,Y+1},{X,Y-1}],
lists:filter(fun({_,E}) -> E /= 'invalid' end, [{C, get_value(C, Data)} || C <- Neigbours]).
build_graph(Coords, Data) ->
Graph = digraph:new(),
[digraph:add_vertex(Graph, C) || C <- Coords],
add_edges(Graph, Data, Coords).
make_coords(Coords, Loop) ->
[{X * Loop , Y * Loop} || {X,Y} <- Coords].
add_edges(Graph, Data, []) -> Graph;
add_edges(Graph, Data, [C|Rest]) ->
Neighbors = get_neighbors(C, Data),
[digraph:add_edge(Graph, C, X, V) || {X,V} <- Neighbors],
add_edges(Graph, Data, Rest).
dijkstra(Graph,Start_node_name) ->
Paths = dict:new(),
Unvisited = gb_sets:new(),
Unvisited_nodes = gb_sets:insert({0,Start_node_name,root},Unvisited),
Paths_updated = loop_through_nodes(Graph,Paths,Unvisited_nodes),
Paths_updated.
loop_through_nodes(Graph,Paths,Unvisited_nodes) ->
%% We need this condition to stop looping through the Unvisited nodes if it is empty
case gb_sets:is_empty(Unvisited_nodes) of
false ->
{{Current_weight,Current_name,Previous_node}, Unvisited_nodes_updated} = gb_sets:take_smallest(Unvisited_nodes),
case dict:is_key(Current_name,Paths) of
false ->
Paths_updated = dict:store(Current_name,{Previous_node,Current_weight},Paths),
Out_edges = digraph:out_edges(Graph,Current_name),
Unvisited_nodes_updated_2 = loop_through_edges(Graph,Out_edges,Paths_updated,Unvisited_nodes_updated,Current_weight),
loop_through_nodes(Graph,Paths_updated,Unvisited_nodes_updated_2);
true ->
loop_through_nodes(Graph,Paths,Unvisited_nodes_updated)
end;
true ->
Paths
end.
loop_through_edges(Graph,[],Paths,Unvisited_nodes,Current_weight) ->
Unvisited_nodes;
loop_through_edges(Graph,Edges,Paths,Unvisited_nodes,Current_weight) ->
[Current_edge|Rest_edges] = Edges,
{Current_edge,Current_node,Neighbour_node,Edge_weight} = digraph:edge(Graph,Current_edge),
case dict:is_key(Neighbour_node,Paths) of
false ->
Unvisited_nodes_updated = gb_sets:insert({Current_weight+Edge_weight,Neighbour_node,Current_node},Unvisited_nodes),
loop_through_edges(Graph,Rest_edges,Paths,Unvisited_nodes_updated,Current_weight);
true ->
loop_through_edges(Graph,Rest_edges,Paths,Unvisited_nodes,Current_weight)
end.

10
2021/day15/input.test Normal file
View File

@@ -0,0 +1,10 @@
1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581

100
2021/day15/input.txt Normal file
View File

@@ -0,0 +1,100 @@
6919598227838199913855119231126554696792992136695118448313191841922775524417825151216891429923213541
9837948917619787189935571922197132977185355128371858691255934311214863828372926993213996998139912118
9712819911516295249274925911896922213911165843181262181868447395254293349493421938929117229988638933
2476951876931175825312533142569137931721739713725799446851119715122115753938166842994429692731365577
3691396937919199853599315812613951281125263711868971256541511653441136543245312424117567151668999674
9294972854229491498411271321351998983919929272128753711198282397882539157287554149474186951291188213
1135428214811459993621216218435832221856114139399136248687314682119118892393618575918692412341569411
2929921158912711182518311271272489732271565129299979967487113812154971756485549913921162939114391994
5735115881479239217981525718898929221191614222551693914913779439617933359521941311111857328992347824
1324749414111313198724813856727141934339899617632138746132396173529281922347716643138211113979119317
3263594941789195782731783751728147419342113519153994137499331274281145119193372917298632271917871525
5479228191148416221119313323857818519129966727666999721348148577292717477671479138864751785262494159
7796954213299199792437719283546721912268871561199118418913219166184792518146351339119739123994185981
9629911853953289553892412891922852724926162185929113819714489559692115112436841311998121591212249911
2328397217172391111288411918123121111329776726473176893942742194591917882178943718116232271214679483
8741141538382111791315111111217879577863971972167912427154411516117129128518217911997124249159922143
1112181727959169888722989121578121121151936427211518922174664147225132238128294879313132991431289481
3747188357529199195611794131377544398823262189627134618228417441399177613261778632518726968681261168
2481629985392983495331692197839119129614185425229598989835611557184114492293122195456638299631886877
9147391211998228191112524911758739341511911573198239147932292971618769152596224169136819211191864121
5339661183639791381383226488915834355926218173956911914294222986717347842733923158213319912313779114
5243921116119511826295361157329514912924232445973183228141342999868999739939499749595714929628949881
1717822297616989111681634446964759597245148141299649442375393616675299961783422585213969182389813979
9223718278792883969179179831171225547156272493833129568562192687845341671181118782551343181335147329
2949471233325124981953749291711218145971445981149411417976569225114219698356762679863952545995247124
5813891161912133536215537881164329141679198579211417483995393171751229139515148551616451451699471962
9119929859113721717292587192359667211794197356859166313415988219993559879467128483625838972963998323
3895252513734165951664259349139491161549113632418318988572115611474628679584659333822336264442417161
1321331549981649293931789932115621285146921639311329258269531211367526813124695472815288349283153957
9422143143834321616229212182481242959489182311359152235561234325491988881677689362294958313949842287
2933761954489328463913592166236523429629187282841912685667184712699837199911744132197611144273159928
9154223693315635418997851912395881642814193154944229782123418943428143338499556944668943742669929821
7139199155869873192534891585999171659544292341128472349512234761139621941897245995229121715921128221
6121476298449615119179315279931141828241794783538353767662277163821548137442111115139516117411432154
2721461614458352311522959322145231893925321191149936561182971937587678991778119969116199785178211249
2487528361345231828917513711239639891526811157458691118988793531821939487349991122139681411829212122
8196784988189916854591415361246889241677468137989661782462692224114367584511836128916614929335987963
1428262253911238199139222239127987864548198367553991618567992112895712539846223268343291112612477881
4311151291221542315119195139919638851217471142313611628999671999898223151846129413511721416129385444
9223929419139196512617954741195118176182238863959367576997199569784421619179812898678142615193816961
3739957281196232999991168188488998188924191959881122119917862162473281529652914854499515417543148211
1169927398515215962874725929618422947517373431917599117392259119991783219193841762221551623313812112
1779521141994763421294833117197299835113728789243129423866794976144315588151693917287864658143995545
1159529199535138199525951914847892791117273918293125411365889356724137416981217218648382141469719663
1441364449664913814639642968343767978911851669683136385812815592539216123382714745918827782372785978
6318957234985141489118421889191571779911215699151212991414982923995699851169649235572492514461152781
7412156483212717161922514861277814977411642186522941564119197181981973336314373991372153411986995122
8897991112125241713878834617986429813629284553444782988769119316585492828131921114225955339181119115
7125797134691266318245163258271753447285747349147564189981125236198721219161583235846326176241283216
9525321171524757914385236188595897464111726911869954146959524288653932322972921175292381219559151292
3194414111319217199913317211199349199115439486152468914947617154512189983891512878579271819721897263
2491297212663627482329238221159172168981257191127613528687982291228575192766566677617649837761491989
1121617881229121329144711662747663125911994277165915132843328895684121414218596361211122111151522917
1162139629471896711146596151128354981329212568252314552651841992789919922154257915321939255343321996
8957911396911314198222223175527176652889162319834385792196891372879635461922911398421776885879797419
7322963541269954962232189653112791497811679512721118141634598993612942952829283995138219829599889896
1569981859182313594573978911399869123929216923327226499129485126875325886837652725166648848111998112
1288121399799771382611161143238967371619191852948117758798124866815182266412112994241352156467592687
9782613685639942816392876435869597448311475929186556881281992238479474821817198267189176811611345259
8297985291593249832442977492543196751332831189541119469439887728521432991519343374611228237815267521
4523444992382282221121212292493497226928544945515424945782491119898752191347166219638988944397819329
1194152129661126528417217522222823524312191626887412455713921129631844996221721711241299731957631929
1781148994623342655141379243991813598498169894269285915113668982571141718118953985931825748891192931
7833796895687353814141792216629798237329497911457911619894313529713318488672351472297297179132273189
9926932996114129354986957691171917584919694139244291829925819193912511541921314292341872312211981115
2226319158194127721821519888721116941969121519196797413362226317939127758283193749485693516626493951
3879811393834677889446991895193312948783741921874992118657173911651519457119526249932991374694221158
3978213824919914931146214425131552342993968699129184834945118939217714393215687129491255112693917989
2158824391323818951718191147228251313192392116229926329592191642213389282938125431317515594129855892
2451172759927711235717449878121951114556117149429163518191331765282139179182223474536877622144431352
2329714311789716815472699771921951445911563498316498268435161242192511134612561842937129461433486692
9129479162281325294261155111911112642211493851211871231213119335358891917149811789318556889897859341
3131721472764729312915112753898151151419189179139342154299471832731815961421341134532764798679814835
2217431514225191812445931219331361111219893144143242969585922236148982273386967781788171191337195416
1488382763322171811791496513637271436981329581196884183931387898461131393171817212859131421121588819
3919585217425217131651936339227398135223761428891742188679177616726195628645462878211341521251196219
1912957445827151319119291131211879781559926431573113691921911897931126976153352174896222328435211744
8323394392199159213314229519951213933192989466113182874918939393519799992338482811596611494443251292
9984916453772991188215712124613985265583131698589662217749113142971842194779131373528882783188719171
3913899817991926921213654613559196179434112197559381516917322458299126529795921728131229913442812145
5261955321792184295644715972199271318912197112951581231816254223846887618715212638468619569563671225
9917489994523968382612199487887184382861222418313922422473349162379172311619221982567741824957119114
9968113457218183711391471141522113356149799928981688713318973119319334121489381212791911983159993251
5249142618957491198134219822522879839256251251436381811362976119514169213884284373893443751176727125
2392796498327162272298169491815314812269718889131918964451489919132342117242821633487187151658118395
2249487296138221889993479576818554862713916146291439161279886228579321318212135384293111391332314217
8897514868449987835128195533898941832793897879991713214683219511961725984113517647629518912372993316
1222365183812221239236493126981329745983157171198118191517444419871498512716164392661878952149182524
4629547769226193136881192975138212468396429891334928131276933521182542469561849129314987648579679814
4749932538499119949794629935997432846571872718898849574149926819691699199813998733192839462193345835
9591811516417941413919173999998125925256922487211975464577143226941827972121634167224618848544866381
1199639929547111431756233793468711319694611716322117618413912797189249351723264174991798896126128931
9148618989823822894126381717841681947679515811112512179728652138551112276241388773414937399838169113
2116766171211521721492313143976327275198231584381986141259139981152183551411875421171911111231991471
9989831137686686132681193914183774211627118849879121936974812614974731981977534928127129133558532219
4741174282322196153167332691899826553963194736319492127196372119621459827218931141194633228429712327
8911816487224543464638721721725597897179615822212948111174159112193164482824873198414218689949816972
9435522297626213549132166931213828698726112979125659542928778787719513418334539737811551126112515196
7992595817832629549819319199131117919697522116215291142239947517891729618121315294175432217519225146
1211761163187331332248351681117516631676788555961569685827143481198812137751721875926238173159343258

179
2021/day16/day16.erl Normal file
View File

@@ -0,0 +1,179 @@
%% to compile: erlc day3A.erl
%% to run: erl -noshell -s day5 solve
%%
-module(day16).
-compile(export_all).
-export ([solve/0, solve/1, solve/2]).
-export ([read_input/0]).
solve() ->
solve(['1']),
solve(['2']),
init:stop().
solve(A) ->
solve(A, read_input()).
solve(['1'], D) ->
io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
solve(1, D) ->
solution1(D);
solve(['2'], D) ->
io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
solve(2, D) ->
solution2(D).
read_input() ->
{ok, IO} = file:open("input.txt", 'read'),
{ok, Line} = file:read_line(IO),
file:close(IO),
hexstr_to_bin(string:strip(Line, 'both', $\n)).
hexstr_to_bin(S) ->
hexstr_to_bin(S, []).
hexstr_to_bin([], Acc) ->
list_to_binary(lists:reverse(Acc));
hexstr_to_bin([X,Y|T], Acc) ->
{ok, [V], []} = io_lib:fread("~16u", [X,Y]),
hexstr_to_bin(T, [V | Acc]);
hexstr_to_bin([X|T], Acc) ->
{ok, [V], []} = io_lib:fread("~16u", lists:flatten([X,"0"])),
hexstr_to_bin(T, [V | Acc]).
bin_to_hexstr(Bin) ->
lists:flatten([io_lib:format("~2.16.0B", [X]) ||
X <- binary_to_list(Bin)]).
solution1(Input) ->
D = unpack(Input, [], not is_zero_bitstring(Input)),
io:format("Pkt: ~p~n", [D]),
count_versions(D, 0).
solution2(Input) ->
D = unpack(Input, [], not is_zero_bitstring(Input)),
io:format("Pkt: ~p~n", [D]),
calc(D).
calc({_,literal, V}) ->
V;
calc({_,Op, V}) ->
?MODULE:Op(V);
calc([{_,Op, V}]) ->
?MODULE:Op(V).
sum(Args) ->
io:format("sum: ~p~n", [Args]),
lists:foldl(fun(X, Acc) -> calc(X) + Acc end, 0, Args).
product(Args) ->
io:format("product: ~p~n", [Args]),
lists:foldl(fun(X, Acc) -> calc(X) * Acc end, 1, Args).
min(Args) ->
io:format("min: ~p~n", [Args]),
lists:min([calc(X) || X <- Args]).
max(Args) ->
io:format("max: ~p~n", [Args]),
lists:max([calc(X) || X <- Args]).
lt([A,B] = Args) ->
io:format("lt: ~p~n", [Args]),
case calc(A) < calc(B) of
'true' -> 1;
'false' -> 0
end.
gt([A,B] = Args) ->
io:format("gt: ~p~n", [Args]),
case calc(A) > calc(B) of
'true' -> 1;
'false' -> 0
end.
eq([A,B] = Args) ->
io:format("eq: ~p~n", [Args]),
case calc(A) == calc(B) of
'true' -> 1;
'false' -> 0
end.
count_versions([{Ver, Type, Rest}|T], Acc) ->
count_versions(T, count_versions(Rest, Acc) + Ver);
count_versions(_, Acc) ->
Acc.
is_zero_bitstring(BitString) ->
Size = erlang:bit_size(BitString),
<<0:Size>> =:= BitString.
unpack(Data, [], 'false') ->
Data;
unpack(Input, Acc, 'false') ->
Acc;
unpack(Input, Acc, 'true') ->
{{Ver, Type, Data}, Rest} = unpack(Input),
io:format("unpacking data: ~p~n", [Data]),
lists:reverse(unpack(Rest, Acc ++ [{Ver, Type, unpack(Data, [], is_bitstring(Data) andalso not is_zero_bitstring(Data))}], not is_zero_bitstring(Rest))).
%% Literal
unpack(<<V:3, 4:3, Rest/bitstring>>) ->
io:format("V:~p, T:literal~n", [V]),
unpack_literal(V, Rest);
%% Operator length type id 0
unpack(<<V:3, T:3, 0:1, Rest/bitstring>>) ->
io:format("V:~p, T:operator I:0~n", [V]),
unpack_operator_0(V, T, Rest);
%% Operator length type id 1
unpack(<<V:3, T:3, 1:1, Rest/bitstring>>) ->
io:format("V:~p, T:operator I:1~n", [V]),
unpack_operator_1(V, T, Rest).
unpack_literal(V, Pkt) ->
unpack_literal(V, Pkt, <<>>, 0).
unpack_literal(V, <<1:1, Value:4, Rest/bitstring>>, Acc, Count) ->
unpack_literal(V, Rest, <<Acc/bitstring, Value:4>>, Count + 1);
unpack_literal(V, <<0:1, Value:4, Rest/bitstring>>, Acc, Count) ->
L = <<Acc/bitstring, Value:4>>,
Size = (Count + 1) * 4,
io:format("unpack_literal value: ~p size:~p rest:~p~n", [Value, Size, Rest]),
<<X:(Size)>> = L,
{{V, literal, X}, Rest}.
unpack_operator_0(V, T, <<Length:15, Rest0/bitstring>>) ->
io:format("operator0 length:~p~n", [Length]),
<<Pkt:(Length)/bitstring, Rest/bitstring>> = Rest0,
{Rest1, Decoded} = unpack_len(Length, Rest0, []),
{{V, operator_type(T), Decoded}, Rest1}.
unpack_operator_1(V, T, <<Num:11, Rest/bitstring>>) ->
{Rest1, Decoded} = unpack_count(Num, Rest, []),
io:format("operator1 num of packets:~p Decoded:~p, Rest:~p~n", [Num,Decoded,Rest1]),
{{V, operator_type(T), Decoded}, Rest1}.
unpack_len(0, Pkt, Acc) ->
{Pkt, Acc};
unpack_len(Length, Pkt, Acc) ->
{L, R} = unpack(Pkt),
io:format("unpack_len: length:before ~p after: ~p~n", [Length, Length - bit_size(Pkt) + bit_size(R)]),
unpack_len(Length - bit_size(Pkt) + bit_size(R), R, Acc ++ [L]).
unpack_count(0, Pkt, Acc) ->
{Pkt, Acc};
unpack_count(Num, Pkt, Acc) ->
{L, R} = unpack(Pkt),
unpack_count(Num - 1, R, Acc ++ [L]).
operator_type(0) -> 'sum';
operator_type(1) -> 'product';
operator_type(2) -> 'min';
operator_type(3) -> 'max';
operator_type(5) -> 'gt';
operator_type(6) -> 'lt';
operator_type(7) -> 'eq'.

1
2021/day16/input.txt Normal file
View File

@@ -0,0 +1 @@
420D50000B318100415919B24E72D6509AE67F87195A3CCC518CC01197D538C3E00BC9A349A09802D258CC16FC016100660DC4283200087C6485F1C8C015A00A5A5FB19C363F2FD8CE1B1B99DE81D00C9D3002100B58002AB5400D50038008DA2020A9C00F300248065A4016B4C00810028003D9600CA4C0084007B8400A0002AA6F68440274080331D20C4300004323CC32830200D42A85D1BE4F1C1440072E4630F2CCD624206008CC5B3E3AB00580010E8710862F0803D06E10C65000946442A631EC2EC30926A600D2A583653BE2D98BFE3820975787C600A680252AC9354FFE8CD23BE1E180253548D057002429794BD4759794BD4709AEDAFF0530043003511006E24C4685A00087C428811EE7FD8BBC1805D28C73C93262526CB36AC600DCB9649334A23900AA9257963FEF17D8028200DC608A71B80010A8D50C23E9802B37AA40EA801CD96EDA25B39593BB002A33F72D9AD959802525BCD6D36CC00D580010A86D1761F080311AE32C73500224E3BCD6D0AE5600024F92F654E5F6132B49979802129DC6593401591389CA62A4840101C9064A34499E4A1B180276008CDEFA0D37BE834F6F11B13900923E008CF6611BC65BCB2CB46B3A779D4C998A848DED30F0014288010A8451062B980311C21BC7C20042A2846782A400834916CFA5B8013374F6A33973C532F071000B565F47F15A526273BB129B6D9985680680111C728FD339BDBD8F03980230A6C0119774999A09001093E34600A60052B2B1D7EF60C958EBF7B074D7AF4928CD6BA5A40208E002F935E855AE68EE56F3ED271E6B44460084AB55002572F3289B78600A6647D1E5F6871BE5E598099006512207600BCDCBCFD23CE463678100467680D27BAE920804119DBFA96E05F00431269D255DDA528D83A577285B91BCCB4802AB95A5C9B001299793FCD24C5D600BC652523D82D3FCB56EF737F045008E0FCDC7DAE40B64F7F799F3981F2490

68
2021/day17/day17.erl Normal file
View File

@@ -0,0 +1,68 @@
%% to compile: erlc day3A.erl
%% to run: erl -noshell -s day5 solve
%%
-module(day17).
-export ([solve/0, solve/1, solve/2]).
-compile ([export_all]).
solve() ->
solve(['1']),
solve(['2']),
init:stop().
solve(A) ->
solve(A, read_input()).
solve(['1'], D) ->
io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
solve(1, D) ->
solution1(D);
solve(['2'], D) ->
io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
solve(2, D) ->
solution2(D).
solution1({X,Y}) ->
Xs = find_x(X),
Ys = find_y(Y),
{T, X1, Y1} = lists:max([{Key, X1, proplists:get_value(Key,Ys)} || {Key, X1} <- Xs, lists:keysearch(Key, 1, Ys) /= false]),
y_max(T,Y1,0).
solution2({X,Y}) ->
Xs = find_x(X),
Ys = find_y(Y),
length(lists:usort([{X,Y} || {Ty, Y} <- Ys, {T,X} <- lists:filter(fun({T,X}) -> T == Ty end, Xs)])).
read_input() ->
{{124,174},{-123, -86}}.
%% {{20,30},{-10, -5}}.
find_x({Xmin, Xmax}) ->
[ {T, Xstart} || Xstart <- lists:seq(0,400), T <- lists:seq(1,1000), x(Xstart, T) >= Xmin, x(Xstart, T) =< Xmax ].
find_y({Ymin, Ymax}) ->
[ {T, Ystart} || Ystart <- lists:seq(-400,400), T <- lists:seq(1,1000), y(Ystart, T) >= Ymin, y(Ystart, T) =< Ymax ].
x(Xstart, T) ->
Last =
case (Xstart - T + 1) of
L when L < 0 -> 0;
L -> L
end,
(Xstart - Last + 1) * (Xstart + Last) div 2.
y(Ystart, T) ->
Last = (Ystart - T + 1),
(Ystart - Last + 1) * (Ystart + Last) div 2.
y_max(0, _, Ymax) -> Ymax;
y_max(T, Y, Ymax) ->
NewY = y(Y, T),
NewMax =
case NewY of
M when M > Ymax -> M;
_ -> Ymax
end,
y_max(T-1, Y, NewMax).

26
2021/day17/diagram.txt Normal file
View File

@@ -0,0 +1,26 @@
1 2 3
4 0123456789012345678901234567890
3 .............#....#............
2 .......#..............#........
1 ...............................
0 S........................#.....
-1 ...............................
-2 ...............................
-3 ...........................#...
-4 ...............................
-5 ....................TTTTTTTTTTT
-6 ....................TTTTTTTTTTT
-7 ....................TTTTTTTT#TT
-8 ....................TTTTTTTTTTT
-9 ....................TTTTTTTTTTT
-10 ....................TTTTTTTTTTT
T X y
0 0 0 = 0
1 7 +6 = 7
2 13 +5 = 7 + 6
3 18 +4 = 7 + 6 + 5
4 22 +3 = 7 + 6 + 5 + 4
5 25 +2
6 27 +1
7 28 +0

1
2021/day17/input.txt Normal file
View File

@@ -0,0 +1 @@
target area: x=124..174, y=-123..-86

130
2021/day18/day18.erl Normal file
View File

@@ -0,0 +1,130 @@
-module(day18).
-export ([solve/0, solve/1]).
-compile ([export_all]).
solve() ->
solve(['1']),
solve(['2']),
init:stop().
solve(['1']) ->
io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1)]);
solve(1) ->
solution1();
solve(['2']) ->
io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2)]);
solve(2) ->
solution2().
solution1() ->
{ok, IO} = file:open("input.txt", 'read'),
Ans = maybe_reduce(read_line(IO), IO),
file:close(IO),
magnitude(Ans).
solution2() ->
{ok, IO} = file:open("input.txt", 'read'),
Numbers = read_all_lines(read_line(IO), IO, []),
file:close(IO),
io:format("total:~p lines: ~p~n", [length(Numbers), Numbers]),
max_magnitude(Numbers).
read_all_lines('eof', _IO, Acc) ->
Acc;
read_all_lines(Line, IO, Acc) ->
read_all_lines(read_line(IO), IO, [Line|Acc]).
read_line(IO) ->
case file:read_line(IO) of
{ok, Line} ->
{ok, Tokens, _} = erl_scan:string(Line ++ "."),
{ok, Term} = erl_parse:parse_term(Tokens),
Term;
'eof' -> 'eof'
end.
max_magnitude(Numbers) when is_list(Numbers) ->
lists:max([ max_magnitude(lists:split(I, Numbers)) || I <- lists:seq(1, length(Numbers))]);
max_magnitude({List1, List2}) ->
[H|T] = lists:reverse(List1),
max_magnitude(H, T ++ List2).
max_magnitude(Number, Rest) ->
lists:foldl(fun(N, MaxMag) ->
case magnitude(reduce([Number, N])) of
Mag when Mag > MaxMag -> Mag;
_ -> MaxMag
end
end, 0, Rest).
magnitude(A) when is_integer(A) -> A;
magnitude([A,B]) ->
(3 * magnitude(A)) + (2 * magnitude(B)).
maybe_reduce(A, IO) ->
case read_line(IO) of
'eof' -> A;
B ->
maybe_reduce(reduce([A,B]), IO)
end.
reduce(N) ->
case maybe_explode(N, 0) of
{true, New, _, _} ->
reduce(New);
false ->
case maybe_split(N) of
{true, New} ->
reduce(New);
false ->
N
end
end.
maybe_explode([A,B], Depth) when Depth >= 4, is_integer(A), is_integer(B) ->
{true, 0, A, B};
maybe_explode([A,B], Depth) ->
case maybe_explode(A, Depth+1) of
{true, New, AddA, AddB} ->
{true, [New, add_explode({b, AddB}, B)], AddA, 0};
false ->
case maybe_explode(B, Depth+1) of
{true, New, AddA, AddB} ->
{true, [add_explode({a, AddA}, A), New], 0, AddB};
false ->
false
end
end;
maybe_explode(N, _) when is_integer(N) ->
false.
add_explode({_, Add}, Num) when is_integer(Num) ->
Add + Num;
add_explode({b, Add}, [A,B]) ->
[add_explode({b, Add}, A), B];
add_explode({a, Add}, [A,B]) ->
[A, add_explode({a,Add}, B)].
maybe_split(N) when is_integer(N) ->
case N > 9 of
true ->
Left = N div 2,
Right = case Left*2 == N of true -> Left; false -> Left+1 end,
{true, [Left, Right]};
false ->
false
end;
maybe_split([A, B]) ->
case maybe_split(A) of
{true, NewA} ->
{true, [NewA, B]};
false ->
case maybe_split(B) of
{true, NewB} ->
{true, [A, NewB]};
false ->
false
end
end.

100
2021/day18/input.txt Normal file
View File

@@ -0,0 +1,100 @@
[[[9,2],[[2,9],0]],[1,[[2,3],0]]]
[[[[2,0],2],[[6,4],[7,3]]],[0,[[3,0],[0,6]]]]
[[[[7,2],2],[9,[6,5]]],[[2,4],5]]
[[[[7,8],2],1],[[[5,4],[2,9]],[7,8]]]
[[[0,7],[1,[6,6]]],[[[0,7],9],4]]
[[[3,[9,6]],[5,1]],[[[0,1],6],[[7,6],0]]]
[[[3,0],[7,[4,0]]],[4,[[6,6],[5,3]]]]
[[[1,[4,8]],[2,[5,8]]],[[[3,6],[2,2]],[[3,8],[7,0]]]]
[9,[[[5,0],[0,3]],[2,[2,6]]]]
[[[3,[8,2]],[[8,0],5]],[[[7,6],[4,9]],[7,5]]]
[[7,[[4,1],9]],[5,1]]
[[[5,[7,5]],1],[8,[5,8]]]
[[[[0,2],7],[[1,4],[9,8]]],[[3,[0,3]],7]]
[[[[4,3],[7,4]],[6,[6,4]]],[8,0]]
[[[1,1],1],[[5,[2,7]],7]]
[[[5,4],5],[[7,[6,3]],[[8,4],6]]]
[[[7,9],[[4,4],[0,0]]],[[[8,6],6],[2,[6,4]]]]
[[[[4,7],[4,9]],3],[[[7,1],[8,6]],[9,[8,2]]]]
[6,[6,[2,9]]]
[[4,[[5,5],[5,0]]],[[[3,4],[9,5]],[8,6]]]
[2,[0,[2,5]]]
[[[4,[7,1]],[2,8]],[[7,0],[[1,6],1]]]
[[[3,4],[[7,8],[6,7]]],[[[6,2],[1,2]],5]]
[[[8,[0,8]],[[9,9],0]],[[[3,5],[4,2]],7]]
[[0,[[0,3],2]],[4,1]]
[[[[0,4],6],7],[[4,[9,1]],3]]
[[0,[[7,0],8]],[2,[8,[8,2]]]]
[[[[3,6],2],[9,4]],[6,[[7,9],[4,5]]]]
[[[[4,9],1],[[9,6],[8,8]]],[[7,[7,6]],[[8,3],[9,0]]]]
[2,0]
[[[[8,2],0],[3,5]],[[7,2],0]]
[[[[1,9],9],6],[9,[[9,3],[8,7]]]]
[[[9,[4,0]],[[7,1],[4,4]]],[[4,[2,3]],[8,7]]]
[[[[9,7],[5,6]],[4,[6,7]]],7]
[5,[[[8,2],8],[6,[7,9]]]]
[0,[[9,[0,1]],[[8,3],7]]]
[[[[4,5],[4,2]],[[5,2],[3,1]]],[[[3,1],[8,5]],8]]
[[0,4],[[2,[2,6]],[[1,1],3]]]
[[[0,8],[7,[5,8]]],7]
[[[7,2],[[6,6],[2,7]]],[[0,[9,3]],2]]
[[[[0,9],2],[[6,0],4]],3]
[[5,[[9,6],9]],[[6,[1,2]],[1,[6,2]]]]
[[[[3,9],5],[9,[7,2]]],[5,[[3,4],[0,6]]]]
[[2,[6,7]],[0,[[2,0],7]]]
[[2,[[5,4],[2,1]]],[2,[[8,7],[5,3]]]]
[[[[0,4],[2,5]],[1,2]],[5,[8,[0,3]]]]
[[[[9,2],[3,2]],[[2,9],4]],5]
[[[[8,9],5],1],[9,3]]
[[5,2],[3,[[8,5],2]]]
[[[0,1],[7,8]],[[[6,2],4],[[6,2],[9,5]]]]
[[[[9,6],5],2],2]
[[[[3,2],3],3],[[[0,1],1],[[8,4],8]]]
[[4,[2,[3,0]]],[[6,[7,0]],6]]
[[6,[[7,8],3]],[[[2,7],4],9]]
[0,2]
[[[9,1],[[3,7],[6,0]]],[[0,[4,1]],[[5,4],7]]]
[[[3,[9,4]],8],[[5,3],2]]
[[6,6],[[[0,5],[0,9]],[[5,5],4]]]
[[[[1,2],4],[[2,4],[8,0]]],[0,[[4,4],[5,8]]]]
[0,[[[9,0],3],[8,4]]]
[[4,5],[[[9,9],[3,5]],[8,[1,4]]]]
[[7,8],[[[3,1],[7,0]],[[4,7],[9,1]]]]
[[4,[2,[1,9]]],[[6,[6,1]],[[0,3],3]]]
[[[5,[0,9]],6],[[[3,4],[9,6]],[[4,0],[0,4]]]]
[[[1,5],[8,[2,8]]],[[5,[0,8]],[[0,7],[4,6]]]]
[[9,[0,2]],[[3,3],[3,1]]]
[[[[2,8],[5,9]],[2,[1,5]]],9]
[[3,[[8,9],[3,1]]],[[[9,0],7],[[0,4],3]]]
[[[[1,5],2],[5,[5,9]]],[5,[[0,1],[0,2]]]]
[6,[[[0,4],8],[[8,2],[5,5]]]]
[[[[7,7],5],[[8,2],7]],[2,5]]
[[[1,1],[[7,8],0]],3]
[[6,[[4,2],9]],[[[5,4],4],3]]
[[[[5,8],3],[[0,4],9]],[[[2,9],2],[3,4]]]
[[0,[4,8]],6]
[[[[9,5],[1,9]],[[3,7],[5,5]]],8]
[[1,9],6]
[[[4,[1,5]],3],0]
[[[2,[6,9]],5],[[5,7],[5,[7,1]]]]
[[[[3,1],[7,3]],[[1,0],[4,6]]],[[[4,9],[4,1]],[9,[2,0]]]]
[[[5,0],[[9,4],6]],[1,[[0,4],[9,9]]]]
[[[[9,8],3],[7,5]],[[[9,5],2],[9,9]]]
[[8,[[8,0],[2,3]]],[[[3,8],[2,6]],[[1,0],0]]]
[[[7,[7,1]],[[6,6],[2,9]]],[[5,[2,0]],[[3,9],[7,4]]]]
[1,[4,[[9,7],[1,3]]]]
[[0,3],[[[4,1],7],[[4,1],[3,0]]]]
[[0,[[7,7],6]],[[4,9],2]]
[[0,8],[4,[4,5]]]
[[[8,[0,5]],[[1,3],[0,5]]],[[2,6],[1,5]]]
[[[[7,6],8],[0,[2,7]]],8]
[8,[[[5,4],8],[[2,1],[7,5]]]]
[[[[7,3],[7,1]],0],[[[7,9],2],3]]
[[8,5],[6,6]]
[[[[5,2],8],7],[[[6,8],[1,0]],[[0,0],1]]]
[[[[1,0],1],6],[9,8]]
[[[[1,2],7],[1,[2,8]]],[[8,1],[[7,5],2]]]
[[0,6],[[2,8],[9,0]]]
[[[0,[7,7]],[2,[0,8]]],[[[7,4],4],[7,[4,0]]]]
[[[2,[9,3]],[[3,7],3]],[[[9,7],[5,6]],8]]
[[2,[[8,7],2]],[[8,[1,8]],[[7,2],1]]]

Binary file not shown.

44
2022/go/day01/day01.go Normal file
View File

@@ -0,0 +1,44 @@
package day01
import (
"sort"
"strings"
"adventofcode2022/utils"
)
type elf struct {
calories int
}
func Part1(input string) int {
elves := common(input)
return elves[0].calories
}
func Part2(input string) int {
elves := common(input)
return elves[0].calories + elves[1].calories + elves[2].calories
}
func common(input string) []elf {
lines := strings.Split(input, "\n")
elves := []elf{}
e := elf{}
for _, line := range lines {
if line == "" {
elves = append(elves, e)
e = elf{}
} else {
e.calories += utils.MustAtoi(line)
}
}
elves = append(elves, e)
sort.Slice(elves, func(i, j int) bool {
return elves[i].calories > elves[j].calories
})
return elves
}

View File

@@ -0,0 +1,43 @@
package day01
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestPart1(t *testing.T) {
r := Part1(`1000
2000
3000
4000
5000
6000
7000
8000
9000
10000`)
assert.Equal(t, 24000, r)
}
func TestPart2(t *testing.T) {
r := Part2(`1000
2000
3000
4000
5000
6000
7000
8000
9000
10000`)
assert.Equal(t, 45000, r)
}

2255
2022/go/day01/input.txt Normal file

File diff suppressed because it is too large Load Diff

89
2022/go/day02/day02.go Normal file
View File

@@ -0,0 +1,89 @@
package day02
import (
"strings"
)
func Part1(input string) int {
var sum int = 0
values := map[string]int{
"Rock": 1,
"Paper": 2,
"Scissors": 3,
}
translateMap := map[string]string{
"X": "Rock",
"Y": "Paper",
"Z": "Scissors",
"A": "Rock",
"B": "Paper",
"C": "Scissors",
}
winOn := map[string]string{
"Rock": "Scissors",
"Paper": "Rock",
"Scissors": "Paper",
}
lines := strings.Split(input, "\n")
for _, line := range lines {
objects := strings.Split(line, " ")
opponent := translateMap[objects[0]]
player := translateMap[objects[1]]
sum = sum + values[player]
if player == opponent {
sum = sum + 3
} else if winOn[player] == opponent {
sum = sum + 6
}
}
return sum
}
func Part2(input string) int {
var sum int = 0
values := map[string]int{
"Rock": 1,
"Paper": 2,
"Scissors": 3,
}
translateMap := map[string]string{
"X": "Lose",
"Y": "Draw",
"Z": "Win",
"A": "Rock",
"B": "Paper",
"C": "Scissors",
}
winOn := map[string]string{
"Rock": "Paper",
"Paper": "Scissors",
"Scissors": "Rock",
}
loseOn := map[string]string{
"Rock": "Scissors",
"Paper": "Rock",
"Scissors": "Paper",
}
lines := strings.Split(input, "\n")
for _, line := range lines {
objects := strings.Split(line, " ")
opponent := translateMap[objects[0]]
result := translateMap[objects[1]]
if result == "Draw" {
sum = sum + 3 + values[opponent]
} else if result == "Win" {
sum = sum + 6 + values[winOn[opponent]]
} else {
sum = sum + values[loseOn[opponent]]
}
}
return sum}

View File

@@ -0,0 +1,23 @@
package day02
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1(
`A Y
B X
C Z`)
require.Equal(t, 15, r)
}
func TestPart2(t *testing.T) {
r := Part2(
`A Y
B X
C Z`)
require.Equal(t, 12, r)
}

2500
2022/go/day02/input.txt Normal file

File diff suppressed because it is too large Load Diff

54
2022/go/day03/day03.go Normal file
View File

@@ -0,0 +1,54 @@
package day03
import (
"strings"
// "fmt"
mapset "github.com/deckarep/golang-set/v2"
)
func Part1(input string) int {
var sum int = 0
lines := strings.Split(input, "\n")
for _, line := range lines {
c1 := []rune(line[:len(line)/2])
c1set := mapset.NewSet[rune](c1...)
c2 := []rune(line[len(line)/2:])
c2set := mapset.NewSet[rune](c2...)
for _, v := range c1set.Intersect(c2set).ToSlice() {
sum += getValue(v)
}
}
return sum
}
func getValue(v rune) int {
if v >= 'a' && v <= 'z' {
return int(v) - int('a') + 1
}
if v >= 'A' && v <= 'Z' {
return int(v) - int('A') + 27
}
return 0
}
func Part2(input string) int {
var sum int = 0
var idx int = 0
lines := strings.Split(input, "\n")
for idx=0; idx < len(lines); idx += 3 {
c1 := []rune(lines[idx])
c1set := mapset.NewSet[rune](c1...)
c2 := []rune(lines[idx+1])
c2set := mapset.NewSet[rune](c2...)
c3 := []rune(lines[idx+2])
c3set := mapset.NewSet[rune](c3...)
for _, v := range c1set.Intersect(c2set).Intersect(c3set).ToSlice() {
sum += getValue(v)
}
}
return sum
}

View File

@@ -0,0 +1,29 @@
package day03
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1(
`vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw`)
require.Equal(t, 157, r)
}
func TestPart2(t *testing.T) {
r := Part2(
`vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcj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hZlfZhqHTsTfltHHZfsHH
GbNbsSptQGqsdJCzsddcgzzv
DHRRnmWWmZnmRhllnHnnnMLvvLgcTVvjVhCTvgzcJgLj
RnWMlDZRlnHlmHWBFwGQqNGGPNQzPGqFwz
vSGvHpJnBLbGHBNCgfDzzChDgbCfzT
wFRslqmqTRgggQghPmQf
qjRFMjWqNNMMGHTL
fWGcQGGSRFQZhttZJfSSJflDDrwdClljVrNDdrdCFBCr
MTgvLLPPnHzMbDwdlNbMBwMM
mnTvnnPTcNmmJJWN
qqbbQQnbWrqGgnWqvZpVzMCZjCgfjZCSVM
ldcmDPDhmlFBHPDddLBVFDHLppZpjSCjjNfwNMwCpSMwhCMp
FtDdsHPcHmdHVPLtHsdtBHQnsbvnTRRTRsRRqbqvqWnJ
hhtBtPrgbbhhgjZjjCCHHNpNDHpffHWCvr
LGFLVwswsJMSgFwMMpddSvpHCCdDdvCpvm
sGsFsQLsVsLFnnFTJQthjcjQqhRcBZZtRg

59
2022/go/day04/day04.go Normal file
View File

@@ -0,0 +1,59 @@
package day04
import (
"strings"
"strconv"
// "fmt"
mapset "github.com/deckarep/golang-set/v2"
)
func Part1(input string) int {
var count int = 0
lines := strings.Split(input, "\n")
for _, line := range lines {
pairs := strings.Split(line, ",")
pair1 := strings.Split(pairs[0], "-")
pair2 := strings.Split(pairs[1], "-")
p1set := mapset.NewSet[int](Range(pair1[0], pair1[1])...)
p2set := mapset.NewSet[int](Range(pair2[0], pair2[1])...)
if p1set.IsSubset(p2set) || p2set.IsSubset(p1set) {
count++
}
}
return count
}
func Part2(input string) int {
var count int = 0
lines := strings.Split(input, "\n")
for _, line := range lines {
pairs := strings.Split(line, ",")
pair1 := strings.Split(pairs[0], "-")
pair2 := strings.Split(pairs[1], "-")
p1set := mapset.NewSet[int](Range(pair1[0], pair1[1])...)
p2set := mapset.NewSet[int](Range(pair2[0], pair2[1])...)
if len(p1set.Intersect(p2set).ToSlice()) > 0 {
count++
}
}
return count
}
func Range(start string, end string)[]int {
s, _ := strconv.Atoi(start)
e, _ := strconv.Atoi(end)
var r []int
for i := s; i <= e; i++ {
r = append(r, i)
}
return r
}

View File

@@ -0,0 +1,29 @@
package day04
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1(
`2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8`)
require.Equal(t, 2, r)
}
func TestPart2(t *testing.T) {
r := Part2(
`2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8`)
require.Equal(t, 4, r)
}

1000
2022/go/day04/input.txt Normal file

File diff suppressed because it is too large Load Diff

93
2022/go/day05/day05.go Normal file
View File

@@ -0,0 +1,93 @@
package day05
import (
"fmt"
"strings"
"github.com/philhanna/stack"
)
func Part1(input string) (result string) {
result = ""
var stacks [9]stack.Stack[string]
var lineNo int
for i := 0; i < 9; i++ {
stacks[i] = stack.NewStack[string]()
}
lines := strings.Split(input, "\n")
for n, line := range lines {
if line == " 1 2 3 4 5 6 7 8 9 " {
lineNo = n + 2
break
}
for i, r := range line {
if r != ' ' && r != '[' && r != ']' {
stacks[i/4].Push(string(r))
}
}
}
for i := 0; i < 9; i++ {
stacks[i].Reverse()
}
var quantity, from, to int
for _, line := range lines[lineNo:] {
fmt.Sscanf(line, "move %d from %d to %d", &quantity, &from, &to)
for i := 0; i < quantity; i++ {
value, _ := (stacks[from-1]).Pop()
stacks[to-1].Push(value)
}
}
for i := 0; i < 9; i++ {
item, _ := stacks[i].Peek()
result = result + item
}
return
}
func Part2(input string) (result string) {
result = ""
var stacks [9]stack.Stack[string]
tmp := stack.NewStack[string]()
var lineNo int
for i := 0; i < 9; i++ {
stacks[i] = stack.NewStack[string]()
}
lines := strings.Split(input, "\n")
for n, line := range lines {
if line == " 1 2 3 4 5 6 7 8 9 " {
lineNo = n + 2
break
}
for i, r := range line {
if r != ' ' && r != '[' && r != ']' {
stacks[i/4].Push(string(r))
}
}
}
for i := 0; i < 9; i++ {
stacks[i].Reverse()
}
var quantity, from, to int
for _, line := range lines[lineNo:] {
fmt.Sscanf(line, "move %d from %d to %d", &quantity, &from, &to)
for i := 0; i < quantity; i++ {
value, _ := (stacks[from-1]).Pop()
tmp.Push(value)
}
for i := 0; i < quantity; i++ {
value, _ := tmp.Pop()
stacks[to-1].Push(value)
}
}
for i := 0; i < 9; i++ {
item, _ := stacks[i].Peek()
result = result + item
}
return
}

View File

@@ -0,0 +1,17 @@
package day05
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1("")
require.Equal(t, 0, r)
}
func TestPart2(t *testing.T) {
r := Part2("")
require.Equal(t, 0, r)
}

514
2022/go/day05/input.txt Normal file
View File

@@ -0,0 +1,514 @@
[G] [D] [Q]
[P] [T] [L] [M] [Z]
[Z] [Z] [C] [Z] [G] [W]
[M] [B] [F] [P] [C] [H] [N]
[T] [S] [R] [H] [W] [R] [L] [W]
[R] [T] [Q] [Z] [R] [S] [Z] [F] [P]
[C] [N] [H] [R] [N] [H] [D] [J] [Q]
[N] [D] [M] [G] [Z] [F] [W] [S] [S]
1 2 3 4 5 6 7 8 9
move 7 from 6 to 8
move 5 from 2 to 6
move 2 from 4 to 1
move 1 from 4 to 5
move 5 from 7 to 6
move 7 from 6 to 3
move 5 from 9 to 2
move 6 from 2 to 3
move 2 from 7 to 9
move 20 from 3 to 1
move 11 from 1 to 6
move 1 from 9 to 8
move 3 from 8 to 2
move 8 from 1 to 5
move 10 from 8 to 4
move 7 from 6 to 4
move 1 from 8 to 3
move 8 from 1 to 7
move 16 from 4 to 8
move 1 from 9 to 8
move 1 from 5 to 2
move 4 from 7 to 4
move 5 from 6 to 7
move 1 from 6 to 1
move 8 from 7 to 4
move 1 from 6 to 9
move 12 from 4 to 5
move 3 from 2 to 5
move 1 from 6 to 2
move 1 from 3 to 7
move 1 from 3 to 2
move 1 from 9 to 3
move 1 from 7 to 8
move 1 from 7 to 5
move 1 from 3 to 2
move 4 from 5 to 7
move 5 from 5 to 7
move 1 from 4 to 3
move 1 from 3 to 9
move 3 from 1 to 8
move 1 from 9 to 1
move 2 from 2 to 1
move 2 from 2 to 7
move 8 from 8 to 1
move 3 from 5 to 2
move 8 from 7 to 5
move 7 from 1 to 3
move 3 from 1 to 7
move 1 from 1 to 5
move 1 from 3 to 7
move 7 from 5 to 8
move 2 from 2 to 8
move 1 from 3 to 2
move 1 from 2 to 4
move 1 from 4 to 8
move 13 from 8 to 1
move 13 from 5 to 9
move 2 from 5 to 2
move 7 from 9 to 3
move 12 from 8 to 3
move 4 from 9 to 3
move 1 from 3 to 4
move 2 from 2 to 3
move 1 from 1 to 6
move 1 from 2 to 3
move 1 from 5 to 9
move 7 from 7 to 4
move 10 from 1 to 8
move 1 from 1 to 4
move 1 from 9 to 5
move 2 from 5 to 1
move 1 from 6 to 5
move 3 from 8 to 9
move 5 from 4 to 3
move 4 from 4 to 1
move 7 from 1 to 6
move 2 from 5 to 7
move 35 from 3 to 4
move 4 from 9 to 1
move 19 from 4 to 8
move 1 from 7 to 6
move 1 from 9 to 2
move 10 from 4 to 5
move 2 from 4 to 7
move 3 from 4 to 3
move 1 from 2 to 8
move 1 from 1 to 9
move 3 from 3 to 6
move 4 from 8 to 6
move 4 from 5 to 2
move 2 from 8 to 3
move 3 from 5 to 9
move 12 from 6 to 1
move 8 from 8 to 6
move 2 from 9 to 1
move 1 from 4 to 1
move 1 from 3 to 8
move 3 from 7 to 8
move 2 from 9 to 7
move 1 from 6 to 7
move 10 from 6 to 8
move 4 from 2 to 5
move 1 from 3 to 7
move 7 from 5 to 7
move 13 from 8 to 1
move 29 from 1 to 4
move 8 from 7 to 8
move 1 from 1 to 3
move 3 from 7 to 6
move 1 from 1 to 9
move 15 from 4 to 1
move 1 from 3 to 6
move 10 from 1 to 6
move 10 from 6 to 7
move 1 from 4 to 9
move 1 from 9 to 1
move 1 from 9 to 7
move 6 from 7 to 8
move 1 from 1 to 6
move 5 from 6 to 5
move 21 from 8 to 9
move 5 from 1 to 9
move 2 from 9 to 5
move 3 from 5 to 6
move 3 from 7 to 9
move 4 from 4 to 6
move 6 from 8 to 7
move 6 from 6 to 3
move 2 from 7 to 9
move 1 from 7 to 2
move 6 from 3 to 2
move 1 from 6 to 4
move 4 from 5 to 9
move 1 from 4 to 5
move 9 from 4 to 6
move 7 from 6 to 4
move 10 from 9 to 2
move 5 from 7 to 5
move 10 from 2 to 7
move 2 from 5 to 4
move 2 from 5 to 9
move 4 from 9 to 4
move 1 from 8 to 6
move 7 from 7 to 2
move 1 from 5 to 4
move 2 from 7 to 1
move 1 from 5 to 7
move 3 from 6 to 2
move 4 from 4 to 5
move 1 from 2 to 7
move 10 from 4 to 7
move 3 from 7 to 3
move 17 from 9 to 4
move 1 from 1 to 4
move 1 from 1 to 5
move 5 from 2 to 7
move 1 from 9 to 2
move 5 from 4 to 8
move 2 from 9 to 7
move 4 from 8 to 1
move 3 from 4 to 8
move 1 from 2 to 5
move 1 from 9 to 2
move 6 from 4 to 8
move 3 from 7 to 5
move 1 from 4 to 9
move 1 from 9 to 1
move 3 from 1 to 9
move 4 from 8 to 5
move 2 from 9 to 8
move 4 from 2 to 5
move 8 from 7 to 2
move 5 from 8 to 5
move 2 from 7 to 8
move 1 from 3 to 5
move 1 from 1 to 2
move 1 from 1 to 6
move 2 from 3 to 6
move 5 from 2 to 8
move 4 from 7 to 1
move 7 from 8 to 5
move 1 from 1 to 5
move 3 from 8 to 3
move 1 from 9 to 3
move 7 from 2 to 3
move 2 from 2 to 8
move 2 from 4 to 8
move 1 from 8 to 5
move 1 from 1 to 4
move 2 from 4 to 7
move 2 from 7 to 1
move 3 from 2 to 3
move 3 from 5 to 2
move 1 from 8 to 3
move 3 from 3 to 2
move 5 from 2 to 1
move 17 from 5 to 8
move 9 from 8 to 1
move 11 from 3 to 5
move 8 from 8 to 5
move 2 from 8 to 5
move 16 from 1 to 4
move 13 from 4 to 7
move 6 from 5 to 2
move 2 from 4 to 8
move 5 from 7 to 9
move 2 from 1 to 2
move 7 from 7 to 1
move 1 from 1 to 4
move 1 from 9 to 8
move 7 from 2 to 8
move 1 from 4 to 7
move 2 from 9 to 4
move 1 from 4 to 1
move 1 from 3 to 5
move 2 from 9 to 8
move 11 from 8 to 7
move 2 from 6 to 5
move 1 from 6 to 9
move 1 from 1 to 9
move 1 from 9 to 1
move 4 from 1 to 4
move 2 from 1 to 8
move 1 from 1 to 2
move 1 from 9 to 5
move 2 from 4 to 3
move 2 from 2 to 7
move 2 from 3 to 9
move 1 from 9 to 1
move 1 from 9 to 1
move 5 from 5 to 1
move 19 from 5 to 6
move 5 from 1 to 4
move 1 from 2 to 9
move 1 from 1 to 3
move 7 from 5 to 8
move 1 from 3 to 6
move 8 from 7 to 3
move 7 from 4 to 8
move 3 from 8 to 5
move 1 from 4 to 1
move 1 from 9 to 4
move 1 from 4 to 9
move 1 from 5 to 2
move 2 from 5 to 6
move 2 from 8 to 2
move 7 from 8 to 1
move 1 from 1 to 7
move 3 from 6 to 9
move 2 from 3 to 2
move 1 from 2 to 1
move 1 from 8 to 7
move 2 from 9 to 6
move 2 from 9 to 5
move 1 from 5 to 6
move 1 from 2 to 8
move 2 from 1 to 7
move 1 from 4 to 3
move 3 from 2 to 5
move 7 from 1 to 3
move 10 from 3 to 4
move 3 from 5 to 4
move 1 from 3 to 8
move 3 from 3 to 2
move 1 from 8 to 1
move 1 from 1 to 3
move 3 from 8 to 3
move 5 from 4 to 6
move 1 from 2 to 3
move 4 from 6 to 4
move 1 from 5 to 7
move 4 from 3 to 4
move 1 from 2 to 8
move 12 from 7 to 6
move 1 from 8 to 2
move 2 from 2 to 7
move 1 from 8 to 4
move 23 from 6 to 3
move 14 from 3 to 6
move 15 from 4 to 6
move 1 from 8 to 6
move 10 from 3 to 7
move 2 from 4 to 2
move 11 from 7 to 8
move 2 from 2 to 6
move 44 from 6 to 9
move 21 from 9 to 3
move 12 from 3 to 6
move 1 from 7 to 4
move 1 from 4 to 7
move 9 from 3 to 2
move 2 from 8 to 6
move 3 from 2 to 4
move 17 from 9 to 1
move 3 from 4 to 6
move 2 from 2 to 9
move 4 from 9 to 2
move 10 from 6 to 9
move 1 from 7 to 6
move 4 from 9 to 5
move 4 from 2 to 4
move 14 from 1 to 5
move 4 from 4 to 3
move 3 from 2 to 9
move 9 from 9 to 7
move 1 from 2 to 5
move 9 from 8 to 5
move 8 from 7 to 2
move 4 from 3 to 8
move 5 from 6 to 2
move 3 from 1 to 6
move 1 from 7 to 1
move 4 from 2 to 4
move 3 from 6 to 4
move 3 from 8 to 3
move 13 from 5 to 2
move 2 from 3 to 5
move 12 from 5 to 9
move 1 from 3 to 5
move 1 from 5 to 9
move 1 from 8 to 3
move 4 from 9 to 5
move 6 from 4 to 5
move 12 from 9 to 7
move 1 from 9 to 3
move 1 from 3 to 2
move 12 from 5 to 6
move 12 from 7 to 2
move 1 from 3 to 7
move 1 from 4 to 8
move 33 from 2 to 8
move 1 from 7 to 5
move 1 from 1 to 2
move 4 from 5 to 4
move 3 from 2 to 5
move 34 from 8 to 6
move 1 from 4 to 3
move 1 from 5 to 7
move 1 from 7 to 5
move 3 from 4 to 9
move 2 from 9 to 7
move 1 from 9 to 4
move 1 from 3 to 7
move 1 from 5 to 8
move 1 from 5 to 1
move 1 from 5 to 7
move 1 from 4 to 8
move 1 from 1 to 4
move 1 from 4 to 2
move 3 from 7 to 5
move 2 from 8 to 5
move 1 from 2 to 8
move 4 from 6 to 2
move 1 from 8 to 6
move 1 from 7 to 9
move 29 from 6 to 7
move 4 from 2 to 3
move 2 from 5 to 8
move 1 from 9 to 5
move 2 from 8 to 1
move 23 from 7 to 5
move 2 from 6 to 1
move 23 from 5 to 6
move 1 from 3 to 6
move 4 from 5 to 9
move 2 from 1 to 3
move 5 from 3 to 8
move 2 from 6 to 5
move 2 from 1 to 4
move 1 from 9 to 8
move 1 from 9 to 1
move 1 from 4 to 6
move 2 from 5 to 6
move 6 from 7 to 8
move 2 from 9 to 2
move 18 from 6 to 5
move 21 from 6 to 4
move 1 from 1 to 6
move 2 from 6 to 7
move 2 from 7 to 9
move 2 from 2 to 8
move 7 from 4 to 3
move 12 from 5 to 3
move 1 from 9 to 5
move 1 from 9 to 4
move 6 from 5 to 2
move 17 from 3 to 4
move 3 from 4 to 3
move 1 from 2 to 4
move 5 from 2 to 8
move 1 from 5 to 8
move 19 from 8 to 7
move 1 from 3 to 6
move 1 from 8 to 4
move 1 from 6 to 1
move 15 from 4 to 6
move 1 from 1 to 4
move 3 from 3 to 5
move 4 from 6 to 7
move 1 from 4 to 7
move 10 from 6 to 7
move 16 from 4 to 5
move 24 from 7 to 2
move 8 from 7 to 8
move 1 from 4 to 2
move 6 from 8 to 7
move 1 from 8 to 7
move 1 from 6 to 9
move 14 from 5 to 4
move 9 from 7 to 8
move 4 from 5 to 1
move 2 from 1 to 5
move 3 from 8 to 6
move 2 from 6 to 9
move 2 from 2 to 8
move 6 from 2 to 7
move 3 from 4 to 6
move 1 from 3 to 4
move 3 from 5 to 7
move 1 from 6 to 9
move 5 from 7 to 2
move 4 from 9 to 1
move 1 from 7 to 9
move 9 from 8 to 4
move 5 from 1 to 2
move 2 from 6 to 1
move 6 from 4 to 7
move 1 from 7 to 3
move 1 from 3 to 9
move 1 from 9 to 7
move 1 from 6 to 7
move 9 from 4 to 5
move 7 from 7 to 9
move 3 from 7 to 5
move 1 from 9 to 2
move 6 from 9 to 8
move 4 from 4 to 5
move 1 from 4 to 2
move 1 from 4 to 2
move 2 from 1 to 2
move 1 from 9 to 8
move 10 from 2 to 4
move 8 from 2 to 7
move 12 from 2 to 9
move 6 from 7 to 4
move 1 from 1 to 2
move 8 from 9 to 8
move 7 from 5 to 1
move 9 from 4 to 3
move 14 from 8 to 4
move 1 from 8 to 4
move 1 from 1 to 5
move 1 from 5 to 2
move 3 from 2 to 4
move 1 from 7 to 1
move 1 from 7 to 3
move 2 from 1 to 7
move 3 from 5 to 7
move 2 from 7 to 6
move 1 from 6 to 5
move 3 from 7 to 1
move 1 from 6 to 8
move 1 from 8 to 7
move 1 from 3 to 6
move 1 from 7 to 1
move 4 from 1 to 4
move 6 from 3 to 2
move 3 from 1 to 2
move 3 from 3 to 6
move 3 from 2 to 6
move 6 from 6 to 5
move 1 from 1 to 4
move 1 from 9 to 6
move 5 from 2 to 1
move 3 from 1 to 2
move 2 from 9 to 8
move 3 from 1 to 5
move 1 from 9 to 7
move 25 from 4 to 1
move 1 from 1 to 7
move 2 from 8 to 3
move 13 from 1 to 9
move 2 from 3 to 5
move 8 from 5 to 9
move 4 from 2 to 1
move 2 from 6 to 7
move 10 from 5 to 9
move 4 from 7 to 2
move 2 from 2 to 3
move 9 from 9 to 2
move 4 from 4 to 5
move 4 from 5 to 4
move 5 from 1 to 4
move 10 from 4 to 5
move 22 from 9 to 1
move 2 from 2 to 7
move 3 from 2 to 1
move 6 from 2 to 6
move 1 from 7 to 1
move 10 from 5 to 7
move 15 from 1 to 4
move 13 from 1 to 5
move 3 from 6 to 8
move 1 from 8 to 9

35
2022/go/day06/day06.go Normal file
View File

@@ -0,0 +1,35 @@
package day06
import (
_ "fmt"
"sort"
"strings"
"github.com/mpvl/unique"
)
func Part1(input string) int {
for i:=4;i<len(input);i++ {
s := input[i-4:i]
if s[0] == s[1] || s[0] == s[2] || s[0] == s[3] || s[1] == s[2] || s[1] == s[3] || s[2] == s[3] {
continue
} else {
return i
}
}
return 0
}
func Part2(input string) int {
for i:=14;i<len(input);i++ {
s := input[i-14:i]
sSlice := strings.Split(s,"")
length := len(sSlice)
sort.Strings(sSlice)
unique.Strings(&sSlice)
if length == len(sSlice) {
return i
}
}
return 0
}

View File

@@ -0,0 +1,17 @@
package day06
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1(`nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg`)
require.Equal(t, 10, r)
}
func TestPart2(t *testing.T) {
r := Part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb")
require.Equal(t, 19, r)
}

1
2022/go/day06/input.txt Normal file
View File

@@ -0,0 +1 @@
srjsssgppnssqzszmzjmjdmmqwqcwqccslsjswjssgbsgsnggqtqnnjznndtndnhddfldfdsfswsjsjjptjpttlwlccpnpgngcncnscncsnnwrwmwggsgdgssvbsstzsstqqrjqqlsqlsqscschhclhccznzcnnzzqppjbpjjqzzbwbqqzdqdjjqtjtbtgtqgtgdgwwsjjbwjjzssrsvsttgqtgglgplgpllcrcncssbrbgrbrllsqlsltthshrrnddwzdzdbbrppdvdqvvpvdvdsslbbmnbnjjrdrnntzzftzftttrsshpspvvrzzqzwzhzszbzjjwqwvqqglgflfwfrfprpddfvdffhzztwtppwwwztzsznzmnnbvbbtqqdhqdqdfffnjnmnlmljmlmnlnddzbbdgdqdnqqtjjtnthttvwwtrwwwgffqcfchfcfwcczhhgjhghpgpwgwffhghzghhtftntnnmlnmlmddqbbfwbfwbwvvfssrggptpltpllbcbzczzlccjgcgvcczjzvvvdtvdvqdqwdqdvdjvddjfdjjqmmfgfsftfzfwzwzfftmfmmqdqccjqcqwwflwlccpssvzzzbnbjnbjjgtgpttbwbrbwrwvrrwccgrgrvvpjvvznvvhddtdldpldppmlplltdllhqhpqhqqbpptgpgjgqjgjffvfdvdttsrsllhzlzrrdrnrjrddqbbjrrvrsstgsttjqjhjbhhnmndmmnrmnnrggmtgmmhshjjfqjjtqtstpstppggtzzrsrwwqffvzvzvqqggqsqtstszttpvtvvvddcncvncvchhnsnpsnnlmnnmqnqjjfwfccmwmbwbswbswwghhzrrptptbbjbtjjgdjgjrgrwgwlglblbnlnbbwnnpbnbmbtmtvvhjjlwlhhszslldwlwdllhjhghqghhqpplhhtjhhnhqhlhjhmmlhlmmrpptvvcczfcccwgcccpgpspdpccfhchffbjbzzwppfbbstbtltpllcssnnctnnqcqhhclhccvlvlffnjjwbwfbfttwvvdvnnnsrstrtmtfthtzzcvzvhzzpmpfpmmmwggdbdqdbbjnbbdqbbrnnnprrwbbcwbbpjjprjjzzvwwvrrthhqvhvnhhzmzszrszsjssclcjjbhjbhjbhjbjhhzbbzttnrnssrbrjbrjjmsmffdlflfzfbzzmtztdthdhldhlddnccgbbmtbbsbzsbzzcsszpzfffprfpfzfrzzhvhffsmmqtjwgjbzhnmrslrmgfjpqcllcgsjdhrshqtlgmqqtfmswfzwtnrswtzdjzclcfmltqgdhcsgvzrdltgfbtqclpppvbqnbqmlhmdbsjbwbdllzpnrwfhmnlgvdwsdjsznnhqzhwntjvcpzdrfwmwwdrttdvzspmbmqggmlmsvwgcjgpvcmplqwfjgpghnfpbctnfhcgngcbdmzhlpcnjpmczzsgfgrdftrzgvmmpdmgcrpcdrjsgczpfjnwpdjpntdngdjwctvcbsjmfwvtsrlhvpswppmfwrwzsbsgbjvljzqjjldmnqnmwsmqnmhmqhhttppbpqlvdcvdbhmbnjzztjrdjdzlvmbdrghtftwdpcwwblsjbgnzwtpztmtmnrpsvzfzncqmrvhcbqcvqvnlngdcllrqlbhjttnmjmhfhdzmjmplcfdqpmwblzsnmpczwcnggcwdvgnjcrrtmpwwqdqpvtbzpdbfnbfcfllntqjlslcsznjvzvsbntrtzwhcbtdmbmwttvhdvdtvrcmprcrrjlgsqddrsmwsrbtbpjrmlbrnsdrjfhjnqjtgjmhzjbjnprvmhtjcdbztwqmrlfflfmcslshtwmwhgvbdslgjhzjlglhllsdphlzngjfwfrlwpnqfhghnqhzhgrszbcwjvlrtmshntszsqplvfbccjwctgtfmqgqjdlgdbwhgvctqtcgfdwvqdwqzddmsbrpftzpqztgzbnplvhftmgpdthnrdhqbltbrmhpcqsfccmqzwmrbnbgbjspslwpjhdqspssqdtnssmjmvzwwfstgzzjrmfczdlznwqpdhbsjqddvffcgfhfdqdrlwcsgcsszdtpqbbsthpwbhdfzmgmcdggfcwcmzfjnfbzbccjhvwhbwfslnqnrwhgrwtlnmrmncnjtbjbdlmqsczppgbcmsdrwlrpjbgrmnhqqfhhsdhmdmpvvpjrnzsvzctmqhpzcvcjfgtlfvqvnvlnprmgrsvrrvtjfndqfsvqdsfbcwlbglmfhfhcfgqdfmclnzhdtppgzzsqgjqncqrbdhlhdjqwjpmbdnfmgdgwbwmnlngnmrhcgqwzvmbjzdvsspjwwdtpnvpftdlqlzfgtscfczsvbrtrqqpgqlvmrtddqplbzsswbgpdzpqfvqpqbndblghmdhmnctdnjbgglmrlvmrmsfgntfdwvqcvvlvbcnwrctvjqhmnsjqccwltbfqpqpmwsfvmnnfqmlmlcchqcdtbvqwcpptvfwrwtbdrlsgnwpmjgnwlprzqjlwqmtmjglbrzlgfbsghwqdmwhrcmfwdmzmflsbngtgndftdpzsqvgqdsfdhplmfcmwpbtvcdmpghmfwqjvhdhfpmbrqpvnbhlftgdtprlztrgnlcldfpjqjqdfrvqtcnzrtjcgzgsslzghlnfhwwjwzdsmpsczclrfmnqjvfmvsqpntsnnnlrfswqtrppzhqgjzlzvrrbhhfhchhvgztpgctcsgssvttszsrdwzwrbmwmspgqhmmfnzqqdbmnbltdmrsvqgddltwczbbjcmplncspgqgmzrndhttsrbvqbpbvhshfqrpqgmmdbhmmtccjcmntmpqhrvhnfnlqqbctsnfzjbphhqwmztgbhqqlbctbsfcszbggzrlcdhwddtjgtqhppzgjsqcddwjsngjrcdflmgwgfnzhjtcwgbqvpwmpgcpdwvqgswwfzcnjgmdpffmqczmsqgpthpmsjlwnrcbzrfshvwftzllwrmfccmlpjnmpjdfpcvjgjpznllmqjwpcflgqgdljtbbjvjlvhhmtvzfnjfnnwrvtlfdbhqphrjghtmlsrplqscsnvjvqdslsbsfzzrjfmchplzgjgdqvzhfphvsjfvnqlgmjfzhrdlmmvfntnzdvrnwqshsmtjnqmwzgpbbzszrsqcvlzjwnmgjhmfqrbvgmfqpswctmvpfcghvdqgstglmzvpfhzfzvhqqdmvrvrttlpwwhqgddzqlrvvdffqtznvlfgjhhmvbmtzjqnnhqzrtbzpqcwpngrdcndcgzwhzgtfwbmwbrpvvczczhwcqwsqzqbqvqftcswtcbzdbpccjhtwbpnwlwwwqwscptlwshrdbmmdcgrmpnnwgjwzszwwdwctfspbfqvdjqtrflshrqlbfgpnrmbszwjpcdzbggphgplcgvwljprzmtncsvfwqchttndhpnzmtdvtjqtcsddtqvcmztmjgwqvjhflrjjtnvfpjrnlvzvwvrpbhrzslmrqqzqhnzqnvtqppmncddphbwwsjczmphsrlltzndtqjgdlqgpnlfcvwntstmrgcrjzmmllpwldnwmwzpvzctmhszspcvtgnqthszzsmtdnzwtfddfctpjhscbqgwfpqmzpvqrzvtbrdjzrqprdgbpmzzfbgqcvcdtsfrffcpqwtvdwvtcqlcsdrzntgrhrspznndslmnvptlphpdqgbblfhmgbpmmfwqzlhvzshhpzgfjldqclngbcbrmmnqqvqmwdnjsglsggqfgjldqfbsqgtrwmpdffqlcwwlfhlpqfgwtssnjwzhgvtwqzmhmgwzwmcggmpmrzqrcsmflqsrbnzvdmjcdbnscstqrqhvddsbjpzwsvzswqhcqmgzlvfcnzjrrffzphmrvdbhqbrwpsfqvfqwhqhcgfvfsfttzcdsrjgjwcgvhllszmplmvgczqsbfldnbvrnqccbprjjdwhmqpdjjrnfdlhzdvlfmrldjlqclbjrrtjfsflphzdcdpfpr

112
2022/go/day07/day07.go Normal file
View File

@@ -0,0 +1,112 @@
package day07
import (
"strings"
"adventofcode2022/utils"
)
type dir struct {
name string
files map[string]int
subdir map[string]*dir
parent *dir
size int
}
func Part1(input string) int {
root := dir{name: "/", files: map[string]int{}, subdir: map[string]*dir{}, parent: nil}
root.parse(input)
sum := 0
find_dirs_part1(&root, 100000, &sum)
return sum
}
func Part2(input string) int {
root := dir{name: "/", files: map[string]int{}, subdir: map[string]*dir{}, parent: nil}
root.parse(input)
unused := 70000000 - root.size
need := 30000000 - unused
dir_size := 0
find_dirs_part2(&root, need, &dir_size)
return dir_size
}
func find_dirs_part1(d *dir, size int, sum *int) {
// recurse into subdir
for _, subdir := range d.subdir {
if (subdir.size) <= size {
*sum += subdir.size
}
find_dirs_part1(subdir, size, sum)
}
}
func find_dirs_part2(d *dir, size int, sum *int) {
// recurse into subdir
for _, subdir := range d.subdir {
if (subdir.size) >= size && (*sum == 0 || (subdir.size) < *sum) {
*sum = subdir.size
}
find_dirs_part2(subdir, size, sum)
}
}
func (root *dir) parse(input string) {
c := root
for _, line := range strings.Split(input, "\n") {
pieces := strings.Split(line, " ")
if pieces[0] == "$" {
if pieces[1] == "cd" {
if pieces[2] == ".." {
c = c.parent
} else if pieces[2] == "/" {
c = root
} else {
c = c.addDirectoryIfMissing(pieces[2])
}
} else if pieces[1] == "ls" {
// no need to do anything
} else {
panic("oops")
}
} else if pieces[0] == "dir" {
c.addDirectoryIfMissing(pieces[1])
} else {
c.addFileIfMissing(pieces[1], utils.MustAtoi(pieces[0]))
}
}
}
func (d *dir) addDirectoryIfMissing(name string) *dir {
t, ok := d.subdir[name]
if !ok {
t = &dir{
name: name,
files: map[string]int{},
subdir: map[string]*dir{},
parent: d,
}
d.subdir[name] = t
}
return t
}
func (d *dir) addFileIfMissing(name string, size int) {
t, ok := d.files[name]
if ok {
if t != size {
panic("oops")
}
} else {
current := d
d.files[name] = size
for current.name != "/" {
current.size += size
current = current.parent
}
current.size += size
}
}

View File

@@ -0,0 +1,63 @@
package day07
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1(
`$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k`)
require.Equal(t, 95437, r)
}
func TestPart2(t *testing.T) {
r := Part2(
`$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k`)
require.Equal(t, 24933642, r)
}

1051
2022/go/day07/input.txt Normal file

File diff suppressed because it is too large Load Diff

89
2022/go/day08/day08.go Normal file
View File

@@ -0,0 +1,89 @@
package day08
import (
_ "fmt"
"adventofcode2022/utils"
"adventofcode2022/utils/inputs"
"adventofcode2022/utils/grid2d"
)
func Part1(input string) int {
grid := inputs.ToGrid2D(input, "\n", "", -1, utils.MustAtoi)
visible := grid2d.NewGrid(grid.SizeX(), grid.SizeY(), false)
for j := 0; j < grid.SizeY(); j++ {
for i := 0; i < grid.SizeX(); i++ {
directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
for _, dir := range directions {
v := true
x := i
y := j
for {
x += dir[0]
y += dir[1]
if x < 0 || x >= grid.SizeX() || y < 0 || y >= grid.SizeY() {
break
}
if grid.Get(i, j) <= grid.Get(x, y) {
v = false
break
}
}
if v {
visible.Set(i, j, true)
break
}
}
}
}
sum := 0
for j := 0; j < visible.SizeY(); j++ {
for i := 0; i < visible.SizeX(); i++ {
if visible.Get(i, j) {
sum++
}
}
}
return sum
}
func Part2(input string) int {
grid := inputs.ToGrid2D(input, "\n", "", -1, utils.MustAtoi)
scenicScore := grid2d.NewGrid(grid.SizeX(), grid.SizeY(), 1)
for j := 0; j < grid.SizeY(); j++ {
for i := 0; i < grid.SizeX(); i++ {
directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
for _, dir := range directions {
score := 0
x := i
y := j
for {
x += dir[0]
y += dir[1]
if x < 0 || x >= grid.SizeX() || y < 0 || y >= grid.SizeY() {
break
}
if grid.Get(i, j) <= grid.Get(x, y) {
score++
break
}
score++
}
scenicScore.Set(i, j, scenicScore.Get(i,j) * score)
}
}
}
max := 0
for j := 0; j < scenicScore.SizeY(); j++ {
for i := 0; i < scenicScore.SizeX(); i++ {
if scenicScore.Get(i, j) > max {
max = scenicScore.Get(i, j)
}
}
}
return max
}

View File

@@ -0,0 +1,27 @@
package day08
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1(
`30373
25512
65332
33549
35390`)
require.Equal(t, 21, r)
}
func TestPart2(t *testing.T) {
r := Part2(
`30373
25512
65332
33549
35390`)
require.Equal(t, 8, r)
}

99
2022/go/day08/input.txt Normal file
View File

@@ -0,0 +1,99 @@
020111211022103023211142403044034010412103202221251542233334311102303044440313120021223120332211221
121001110111201102213124201444431204213221413222211111444444412110041144131210002230130121313101010
112010221202200121420032021412024323255214355122345552225213252324112400440302313420323102103100221
211022232121222123201224234031435144114512425232345144523531533222344004011342234110131312300332202
202103101023303021233104321411251553151424242531344221312225231225524421412434024103021300123300121
202122200002211022342141123051132352344252152315525324551424132421225143201002114204223302333232221
011310312223223421431113235421121321152124551441143435255214322514544552225412313011414423301132102
121331322013001133311000223433443341113554412556562564315233144532455221433431002003332002203013201
003201332004241133340023541532333131413153266664363423353232622124454254554345422200200433100333102
230030131344203011040552414515334144165664524445366334422626244444323115333252423443232113432003211
020300112334333142144323414353551436334563654426436625356343222253643212532215422020214344013310331
220002231221003314452445344223355655546325233543653632544634656464243551334233433413423044300230210
111022100242320043435324555421362243363346366346456252353246655455262455415331454531201000441410231
101232013434204241242451442362524554225656254252456532663634445256345634451144555513214431300213021
021113211441142541244515256653533353262654644343347336234522332254544443346322422154143020040021110
002032342223245141521455555365463263562446777664546776637635443223664266645633333231151132112140113
002033421301452414544444345232465536465366346553375665564756366435442422632435555111445311104203133
332303032232445231354236322622423634433537753546335477544636344436526324435436522445155410213401230
214021124335354212514535634245552337436663757533364556376776733565333462254562365531354214423412431
231123230423124441525624265443647673566756453545563655373357453547537663433453433212213223101140424
100211320333154123522263362425466444634667564437776546465446345667366445453365366551352122420231230
024400401554531424535342424657437377754456437376767656436366374765557746355562226364213315421212320
214442223135544515264335435467756354735433346664764464468465443746334373746425422542525455354340110
141333001441254326655252563743544735555378755475567457777687677357576573543344653346551442221242312
022033123224325536562464253467675635635678458757477754757874576653435356676234462564555551451230022
444402313413432333426636637636453646648557685556587678886878777785454364533433543362622525453201222
031024134513414333456224636475357556855564445765756678575486648885765563445546566235352311454320030
341331341415512452344636337436467675565575756658588888477584775646657736366434365523664142235144413
333344214132152543325563654447567486457556845676545687457688885466457333476777342344625323533242333
203124152315365546566375565336778768544768846599686578655665448478657834657533335544343231212251101
200144235323636235437557635373578555545475587655886585897998654658858755534374677344254563233421200
433243323452635426237436445738684446475489658878699879887988684656474746764334543334452565153341241
340411231113223465344733555465744685569658998876796578688888887678657675875533766464362432543531231
132155112416452662274535754677457567869597559977756878779755568868854644586734466764422245333151550
321153454153653654743477667888756477986578656976558879999589975695487876766664653466625262642234421
414524133155254243564664555445778475666688565697596679558768656758547564888437343772346336642515514
321251321324554554436434474754674597576658986766997798688766897876884764444653674674326233445555243
031553412663524646375654566887688857698655696699699989968699659665774657875735457664452362352111522
121541141642244257534355645887786995858959886778688769889987779898696567777567344373632655621545545
334343242432423553675774445756455759676757789677879778999988695976997447856786357655446656351514552
125145532643224566754564678556569669557567799868776897666898866898879866784847777744353546366314141
045114213352452647446647465888875868689699789677897977779999699895556776458746737674746244442322442
132343555663565436365447746478789879798676878686777999789966769777759954677478745673552645533545344
045253354653642556466557766588567888887978866878777776986676768968695857655674556463732652626443441
324411423536354677366485874488885578788769789998797978797888777868996895476778847746764226464355343
355421453642352476436787475855785669696986976979989787787998669696679989555875747556435562425323311
225422326356526465747344444546866698678986799879779799999876866969999686664477767757535635652555421
215234242322226376376776764668889755898766677787987779877967696689565966757675463574434246652622343
214252444222333767567367778585695867987669688798987987789888698888858597545545475573737453632634414
435144324646623745547785547465689576878976877888878988989877866686976879488454664357347554642541254
424224446333664566656688545685586987987699788897978888788999878967887869445474863534753362524653532
234521532264544735666677658457578679997886798878788998987976677895559685784445835563745433436535545
541253562333326733576345574569866788667878789897999998887996866685657897848485475437744246636412312
531515163362265375476387485646556857878999799999999989879989886696789765664474863474462523344554532
134323536435565375644658845476675857999867789999988888799986676978987577885467643356656525623333421
432434326635433776557758756889896978587689688777989999797796888999765958586488873373565325435254453
352344243543664654777655867556767767686778796989888798998697976755779565488844544677343523234525134
023522455223435563774634466685769765877876776996699877886876668865856964846675357575675235445525211
452211123455454466574537744568597875596879779869788776669767986968956557448486336534544244456115451
154255352645344566574476875484685575595898898697799799688669879869766768688476473673634645556554324
153224532366353377543578485765465665577767776999977978876879865565957587758448456773452265664315213
212223354662352476456344644856876756566976677698968768897897866997679566845464663374352444344522513
333134124655526377555445475778655559695856687767878889687866969787796886748547665457422543622531314
114114243655626456537464558857564557866777897897898988696885586978887448448543375665233363532515252
022123225426235336675765546686448888566865666569876966556979869667956845877753374733454555422452344
105112231544246463366336777688875488697685796985999888976956985978664485756743456372244565641412542
243421525526425322655767646868764584599579555769857975877669799998745668566534743565233224245452434
310412235133463356343754335447454467578555798898788997569756589585876868467475435524433556255213522
122253434533466554567356664688567676567976599967878669868967997845484546736534545734455626245154423
313334534424352263526466637778587787868565658999559897596678677574858776343543534432632333531241224
001031252124265545567437743765668445564487997555965858678954577555545545743366457636433553523254344
044305452425444342246365565576568644874888888677955886697487686854588744354437555336664241413533111
110113123534526242542645447354547688467557884774478677887477777586654656653436654455626314334324023
403311355254242426345425533745657486754657454674877454647844866774463676664344325662334351444144012
114043453225323265365363357353773386544675474785655464585675566555543364665665355442555535443420344
234021355512324262426566274773756436677647664566764646854655875476556464746532226425352124354233001
104234323224222234534254555373773666356744475886877868685764755374634533664662562645321154355101301
413312132345313224565423553463467666456365585778746647466885776356666677636556254365513311121044324
010140223145323354554344523347476477547564757555585887484666633663433654743326266555221322431333120
023311233225342421354662654347733666374666336373663635367447753577353743232632663243333251551031321
143043334422453221246324462653756444767736544367544755375437335646557334655533644454121143303220002
101212344011254432246625336226267546745356655577456676377355677475746633565634244145133154032123242
233244204414154431434433222525444454344635736634774576466473546373725623264634363324244114303014300
010103422332213512154554324533443662535535356636747655647737636354525554536436123454141421414030443
203123300244432323224135253642444433566335637575443374634433336553444225543564152215332533001133230
213003230312403552352142145445635666323653353353657647435752235322633623453542112525124011312421020
120004434213011143254452233425222536464236356544634635324242345464353322232141135221424123200431123
331000214011314431233211121223425334456246345226324246526344536556636556453143153253323114441131132
303123142412333143322451153243464566344362342525524265432552566442626262524431454151443133021301210
220100102032004440315125323552226234566265233246334556355333643662354455122325544112124232340231031
112122312031202424345533512342151435534325334444254264542526645645533111234131131223411304322200110
213031212133401330114433121533455425225634422363334633454623522242353342455454511303033230433202120
223232022333401311421344332255311133421254642562465526534445512134533413153142410113101444330132130
020133013100324344342244215442123125243314222446342424421353134352515124333133430431401122202211032
102300310001014311443112031115242425132234255215315523551534154524134344433432201022200432133000302
001233311232134334100401400151532231322435145412132433235254313414243334103312232304403111313321210
110213022233310011220103432114343112114222424442543155552411511144115122143322304023012132213011210
000220123220323122321103444304134551331233141552114422121151224211122042434324042030120133230110110
020120232301110331441234422110132302233413123211331413433254521355004032312110222131010330301222211

119
2022/go/day09/day09.go Normal file
View File

@@ -0,0 +1,119 @@
package day09
import (
"strings"
"adventofcode2022/utils"
sparsegrid "adventofcode2022/utils/sparseGrid"
)
type rope struct {
size int
posX []int
posY []int
}
func Part1(input string) int {
rope := newRope(2)
grid := sparsegrid.NewGrid(false)
grid.Set(rope.posX[rope.size-1], rope.posY[rope.size-1], true)
for _, line := range strings.Split(input, "\n") {
dx := 0
dy := 0
switch line[0] {
case 'R':
dx = 1
case 'U':
dy = -1
case 'D':
dy = 1
case 'L':
dx = -1
}
n := utils.MustAtoi(line[2:])
for i := 0; i < n; i++ {
// move head
rope.posX[0] += dx
rope.posY[0] += dy
// update tail
rope.updateTail()
grid.Set(rope.posX[rope.size-1], rope.posY[rope.size-1], true)
}
}
return grid.Visited()
}
func Part2(input string) int {
rope := newRope(10)
grid := sparsegrid.NewGrid(false)
grid.Set(rope.posX[rope.size-1], rope.posY[rope.size-1], true)
for _, line := range strings.Split(input, "\n") {
dx := 0
dy := 0
switch line[0] {
case 'R':
dx = 1
case 'U':
dy = -1
case 'D':
dy = 1
case 'L':
dx = -1
}
n := utils.MustAtoi(line[2:])
for i := 0; i < n; i++ {
// move head
rope.posX[0] += dx
rope.posY[0] += dy
// update tail
rope.updateTail()
grid.Set(rope.posX[rope.size-1], rope.posY[rope.size-1], true)
}
}
return grid.Visited()
}
func newRope(size int) *rope {
return &rope{
size: size,
posX: make([]int, size),
posY: make([]int, size),
}
}
func (r *rope) updateTail() {
outer:
for i := 1; i < r.size; i++ {
diffX := utils.Abs(r.posX[i-1] - r.posX[i])
diffY := utils.Abs(r.posY[i-1] - r.posY[i])
if diffX <= 1 && diffY <= 1 {
// no need to update node if it's touching
continue
}
moves := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
for _, move := range moves {
t := utils.Max(
utils.Abs(r.posX[i-1]-r.posX[i]+move[0]),
utils.Abs(r.posY[i-1]-r.posY[i]+move[1]))
if t == 1 {
r.posX[i] = r.posX[i-1] + move[0]
r.posY[i] = r.posY[i-1] + move[1]
continue outer
}
}
moves = [][]int{{1, 1}, {-1, 1}, {1, -1}, {-1, -1}}
for _, move := range moves {
t := utils.Max(
utils.Abs(r.posX[i-1]-r.posX[i]+move[0]),
utils.Abs(r.posY[i-1]-r.posY[i]+move[1]))
if t == 1 {
r.posX[i] = r.posX[i-1] + move[0]
r.posY[i] = r.posY[i-1] + move[1]
continue outer
}
}
panic("unreachable")
}
}

View File

@@ -0,0 +1,25 @@
package day09
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1(
`R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2`)
require.Equal(t, 13, r)
}
func TestPart2(t *testing.T) {
r := Part2("")
require.Equal(t, 0, r)
}

2000
2022/go/day09/input.txt Normal file

File diff suppressed because it is too large Load Diff

77
2022/go/day10/day10.go Normal file
View File

@@ -0,0 +1,77 @@
package day10
import (
"adventofcode2022/utils"
_ "fmt"
"strings"
)
func Part1(input string) int {
lines := strings.Split(input, "\n")
cycle := 0
strength := 0
x := 1
for _, line := range lines {
cmd := strings.Split(line, " ")
switch {
case cmd[0] == "noop":
strength,cycle = cycles_1(1, cycle, strength, x)
case cmd[0] == "addx":
strength, cycle = cycles_1(2, cycle, strength, x)
x += utils.MustAtoi(cmd[1])
}
}
return strength
}
func Part2(input string) string {
lines := strings.Split(input, "\n")
cycle := 0
x := 1
crt := [6][40]string{}
for _, line := range lines {
cmd := strings.Split(line, " ")
switch {
case cmd[0] == "noop":
cycle = cycles_2(1, cycle, x, &crt)
case cmd[0] == "addx":
cycle = cycles_2(2, cycle, x, &crt)
x += utils.MustAtoi(cmd[1])
}
}
output := "\n"
for i:=0;i<6;i++ {
for j:=0;j<40;j++ {
output = output + crt[i][j]
}
output = output + "\n"
}
return output
}
func cycles_1(num int, cycle int, strength int, x int) (int, int) {
for i:=0;i<num;i++ {
cycle++
if cycle == 20 {
strength = strength + (x * cycle)
} else if (cycle - 20) % 40 == 0 {
strength = strength + (x * cycle)
}
}
return strength, cycle
}
func cycles_2(num int, cycle int, x int, crt *[6][40]string) int {
for i:=0;i<num;i++ {
crt_x := cycle / 40
crt_y := cycle % 40
if x-1 == crt_y || x == crt_y || x+1 == crt_y {
crt[crt_x][crt_y] = "#"
} else {
crt[crt_x][crt_y] = " "
}
cycle++
}
return cycle
}

314
2022/go/day10/day10_test.go Normal file
View File

@@ -0,0 +1,314 @@
package day10
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1(
`addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx -35
addx 1
addx 24
addx -19
addx 1
addx 16
addx -11
noop
noop
addx 21
addx -15
noop
noop
addx -3
addx 9
addx 1
addx -3
addx 8
addx 1
addx 5
noop
noop
noop
noop
noop
addx -36
noop
addx 1
addx 7
noop
noop
noop
addx 2
addx 6
noop
noop
noop
noop
noop
addx 1
noop
noop
addx 7
addx 1
noop
addx -13
addx 13
addx 7
noop
addx 1
addx -33
noop
noop
noop
addx 2
noop
noop
noop
addx 8
noop
addx -1
addx 2
addx 1
noop
addx 17
addx -9
addx 1
addx 1
addx -3
addx 11
noop
noop
addx 1
noop
addx 1
noop
noop
addx -13
addx -19
addx 1
addx 3
addx 26
addx -30
addx 12
addx -1
addx 3
addx 1
noop
noop
noop
addx -9
addx 18
addx 1
addx 2
noop
noop
addx 9
noop
noop
noop
addx -1
addx 2
addx -37
addx 1
addx 3
noop
addx 15
addx -21
addx 22
addx -6
addx 1
noop
addx 2
addx 1
noop
addx -10
noop
noop
addx 20
addx 1
addx 2
addx 2
addx -6
addx -11
noop
noop
noop`)
require.Equal(t, 13140, r)
}
func TestPart2(t *testing.T) {
r := Part2(
`addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx -35
addx 1
addx 24
addx -19
addx 1
addx 16
addx -11
noop
noop
addx 21
addx -15
noop
noop
addx -3
addx 9
addx 1
addx -3
addx 8
addx 1
addx 5
noop
noop
noop
noop
noop
addx -36
noop
addx 1
addx 7
noop
noop
noop
addx 2
addx 6
noop
noop
noop
noop
noop
addx 1
noop
noop
addx 7
addx 1
noop
addx -13
addx 13
addx 7
noop
addx 1
addx -33
noop
noop
noop
addx 2
noop
noop
noop
addx 8
noop
addx -1
addx 2
addx 1
noop
addx 17
addx -9
addx 1
addx 1
addx -3
addx 11
noop
noop
addx 1
noop
addx 1
noop
noop
addx -13
addx -19
addx 1
addx 3
addx 26
addx -30
addx 12
addx -1
addx 3
addx 1
noop
noop
noop
addx -9
addx 18
addx 1
addx 2
noop
noop
addx 9
noop
noop
noop
addx -1
addx 2
addx -37
addx 1
addx 3
noop
addx 15
addx -21
addx 22
addx -6
addx 1
noop
addx 2
addx 1
noop
addx -10
noop
noop
addx 20
addx 1
addx 2
addx 2
addx -6
addx -11
noop
noop
noop`)
require.Equal(t, `##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....`, r)
}

140
2022/go/day10/input.txt Normal file
View File

@@ -0,0 +1,140 @@
addx 1
addx 4
addx 21
addx -20
addx 4
noop
noop
addx 5
addx 3
noop
addx 2
addx 1
noop
noop
addx 4
noop
noop
noop
addx 3
addx 5
addx 2
addx 1
noop
addx -37
addx 22
addx -4
addx -14
addx 2
addx 5
addx 3
addx -2
addx 2
addx 5
addx 2
addx -15
addx 32
addx -14
addx 5
addx 2
addx 3
noop
addx -13
addx -2
addx 18
addx -36
noop
addx 11
addx -7
noop
noop
addx 6
addx 22
addx -21
addx 3
addx 2
addx 4
noop
noop
noop
addx 5
addx -16
addx 17
addx 2
addx 5
addx -11
addx 15
addx -15
addx -24
noop
noop
addx 7
addx 2
addx -6
addx 9
noop
addx 5
noop
addx -3
addx 4
addx 2
noop
noop
addx 7
noop
noop
noop
addx 5
addx -28
addx 29
noop
addx 3
addx -7
addx -29
noop
addx 7
addx -2
addx 2
addx 5
addx 2
addx -3
addx 4
addx 5
addx 2
addx 8
addx -30
addx 25
addx 7
noop
noop
addx 3
addx -2
addx 2
addx -10
addx -24
addx 2
noop
noop
addx 2
noop
addx 3
addx 2
noop
addx 3
addx 2
addx 5
addx 2
noop
addx 1
noop
addx 2
addx 8
noop
noop
addx -1
addx -9
addx 14
noop
addx 1
noop
noop

148
2022/go/day11/day11.go Normal file
View File

@@ -0,0 +1,148 @@
package day11
import (
_ "fmt"
"strings"
"sort"
"adventofcode2022/utils"
"math/big"
)
type op int
const (
addition op = iota + 1
multiply
square
)
type monkey struct {
items []*big.Int
operation op
opArg *big.Int
test *big.Int
ifTrue int
ifFalse int
inspected int
}
func Part1(input string) int {
monkeys := parseInput(input)
var level = big.NewInt(0)
for round := 0; round < 20; round++ {
for i, monkey := range monkeys {
for _, item := range monkey.items {
monkeys[i].inspected++
switch monkey.operation {
case addition:
level = new(big.Int).Add(item, monkey.opArg)
case multiply:
level = new(big.Int).Mul(item, monkey.opArg)
case square:
level = new(big.Int).Mul(item, item)
}
level = new(big.Int).Div(level, big.NewInt(3))
t := &big.Int{}
t.Mod(level, monkey.test)
if t.Sign() == 0 {
monkeys[monkey.ifTrue].items = append(monkeys[monkey.ifTrue].items, level)
} else {
monkeys[monkey.ifFalse].items = append(monkeys[monkey.ifFalse].items, level)
}
}
monkeys[i].items = monkeys[i].items[:0]
}
}
sort.Slice(monkeys, func(i, j int) bool {
return monkeys[i].inspected > monkeys[j].inspected
})
return monkeys[0].inspected * monkeys[1].inspected
}
func Part2(input string) int {
monkeys := parseInput(input)
var level = big.NewInt(0)
commonDivisor := big.NewInt(3 * 13 * 19 * 17 * 5 * 7 * 11 * 2)
for round := 0; round < 10000; round++ {
for i, monkey := range monkeys {
for _, item := range monkey.items {
monkeys[i].inspected++
switch monkey.operation {
case addition:
level = new(big.Int).Add(item, monkey.opArg)
case multiply:
level = new(big.Int).Mul(item, monkey.opArg)
case square:
level = new(big.Int).Mul(item, item)
}
level = level.Mod(level, commonDivisor)
t := &big.Int{}
t.Mod(level, monkey.test)
if t.Sign() == 0 {
monkeys[monkey.ifTrue].items = append(monkeys[monkey.ifTrue].items, level)
} else {
monkeys[monkey.ifFalse].items = append(monkeys[monkey.ifFalse].items, level)
}
}
monkeys[i].items = monkeys[i].items[:0]
}
}
sort.Slice(monkeys, func(i, j int) bool {
return monkeys[i].inspected > monkeys[j].inspected
})
return monkeys[0].inspected * monkeys[1].inspected
}
func parseInput(input string) []monkey {
monkeys := []monkey{}
for i, monkeyString := range strings.Split(input, "\n\n") {
for _, line := range strings.Split(monkeyString, "\n") {
if strings.HasPrefix(line, "Monkey") {
monkeys = append(monkeys, monkey{})
} else if strings.HasPrefix(line, " Starting items: ") {
s := strings.TrimPrefix(line, " Starting items: ")
for _, piece := range strings.Split(s, ", ") {
t := utils.MustAtoi(piece)
monkeys[i].items = append(monkeys[i].items, big.NewInt(int64(t)))
}
} else if strings.HasPrefix(line, " Operation: new = ") {
s := strings.TrimPrefix(line, " Operation: new = ")
if strings.HasPrefix(s, "old + ") {
s2 := strings.TrimPrefix(s, "old + ")
monkeys[i].operation = addition
t := utils.MustAtoi(s2)
monkeys[i].opArg = big.NewInt(int64(t))
} else if s == "old * old" {
monkeys[i].operation = square
} else if strings.HasPrefix(s, "old * ") {
s2 := strings.TrimPrefix(s, "old * ")
monkeys[i].operation = multiply
t := utils.MustAtoi(s2)
monkeys[i].opArg = big.NewInt(int64(t))
}
} else if strings.HasPrefix(line, " Test: divisible by ") {
s := strings.TrimPrefix(line, " Test: divisible by ")
t := utils.MustAtoi(s)
monkeys[i].test = big.NewInt(int64(t))
} else if strings.HasPrefix(line, " If true: throw to monkey ") {
s := strings.TrimPrefix(line, " If true: throw to monkey ")
monkeys[i].ifTrue = utils.MustAtoi(s)
} else if strings.HasPrefix(line, " If false: throw to monkey ") {
s := strings.TrimPrefix(line, " If false: throw to monkey ")
monkeys[i].ifFalse = utils.MustAtoi(s)
} else if line == "" {
// do nothing
} else {
panic("unknown input")
}
}
}
return monkeys
}

View File

@@ -0,0 +1,45 @@
package day11
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1(
`Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
`)
require.Equal(t, 10605, r)
}
func TestPart2(t *testing.T) {
r := Part2("")
require.Equal(t, 0, r)
}

55
2022/go/day11/input.txt Normal file
View File

@@ -0,0 +1,55 @@
Monkey 0:
Starting items: 54, 98, 50, 94, 69, 62, 53, 85
Operation: new = old * 13
Test: divisible by 3
If true: throw to monkey 2
If false: throw to monkey 1
Monkey 1:
Starting items: 71, 55, 82
Operation: new = old + 2
Test: divisible by 13
If true: throw to monkey 7
If false: throw to monkey 2
Monkey 2:
Starting items: 77, 73, 86, 72, 87
Operation: new = old + 8
Test: divisible by 19
If true: throw to monkey 4
If false: throw to monkey 7
Monkey 3:
Starting items: 97, 91
Operation: new = old + 1
Test: divisible by 17
If true: throw to monkey 6
If false: throw to monkey 5
Monkey 4:
Starting items: 78, 97, 51, 85, 66, 63, 62
Operation: new = old * 17
Test: divisible by 5
If true: throw to monkey 6
If false: throw to monkey 3
Monkey 5:
Starting items: 88
Operation: new = old + 3
Test: divisible by 7
If true: throw to monkey 1
If false: throw to monkey 0
Monkey 6:
Starting items: 87, 57, 63, 86, 87, 53
Operation: new = old * old
Test: divisible by 11
If true: throw to monkey 5
If false: throw to monkey 0
Monkey 7:
Starting items: 73, 59, 82, 65
Operation: new = old + 6
Test: divisible by 2
If true: throw to monkey 4
If false: throw to monkey 3

18
2022/go/go.mod Normal file
View File

@@ -0,0 +1,18 @@
module adventofcode2022
go 1.19
require (
github.com/alokmenghrajani/adventofcode2022 v0.0.0-20221225182202-291aae949bfb
github.com/deckarep/golang-set/v2 v2.3.1
github.com/mpvl/unique v0.0.0-20150818121801-cbe035fff7de
github.com/philhanna/stack v1.5.0
github.com/stretchr/testify v1.8.2
golang.org/x/exp v0.0.0-20221208152030-732eee02a75a
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

27
2022/go/go.sum Normal file
View File

@@ -0,0 +1,27 @@
github.com/alokmenghrajani/adventofcode2022 v0.0.0-20221225182202-291aae949bfb h1:brhd2lQBATJuzH9JNEoJHeDT0zs5WImcEtRqQ2OzYLw=
github.com/alokmenghrajani/adventofcode2022 v0.0.0-20221225182202-291aae949bfb/go.mod h1:1rWZGu5Q4mtVaXOMj9kUNWcJqNGQJWynsvLmnN3P1Ng=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/deckarep/golang-set/v2 v2.3.1 h1:vjmkvJt/IV27WXPyYQpAh4bRyWJc5Y435D17XQ9QU5A=
github.com/deckarep/golang-set/v2 v2.3.1/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4=
github.com/mpvl/unique v0.0.0-20150818121801-cbe035fff7de h1:D5x39vF5KCwKQaw+OC9ZPiLVHXz3UFw2+psEX+gYcto=
github.com/mpvl/unique v0.0.0-20150818121801-cbe035fff7de/go.mod h1:kJun4WP5gFuHZgRjZUWWuH1DTxCtxbHDOIJsudS8jzY=
github.com/philhanna/stack v1.5.0 h1:GAKwXfNxNPjv6MIDZAoFOTFMKt2wj+63iDpjyz8tapQ=
github.com/philhanna/stack v1.5.0/go.mod h1:w5LpFSK/gkZQdRXU5xvDcvyvVD5VmyfZ3FNZAVmih2s=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/exp v0.0.0-20221208152030-732eee02a75a h1:4iLhBPcpqFmylhnkbY3W0ONLUYYkDAW9xMFLfxgsvCw=
golang.org/x/exp v0.0.0-20221208152030-732eee02a75a/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

127
2022/go/main.go Normal file
View File

@@ -0,0 +1,127 @@
package main
import (
"fmt"
// "math/rand"
"os"
// "strings"
// "time"
"adventofcode2022/utils"
"adventofcode2022/day01"
"adventofcode2022/day02"
"adventofcode2022/day03"
"adventofcode2022/day04"
"adventofcode2022/day05"
"adventofcode2022/day06"
"adventofcode2022/day07"
"adventofcode2022/day08"
"adventofcode2022/day09"
"adventofcode2022/day10"
"adventofcode2022/day11"
)
// Usage: go run main.go <NN>
// assumes input is in day<NN>/input.txt
func main() {
d := day()
fmt.Printf("Running day %02d\n", d)
switch d {
case 1:
fmt.Printf("part 1: %d\n", day01.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %d\n", day01.Part2(utils.Readfile(d)))
case 2:
fmt.Printf("part 1: %d\n", day02.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %d\n", day02.Part2(utils.Readfile(d)))
case 3:
fmt.Printf("part 1: %d\n", day03.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %d\n", day03.Part2(utils.Readfile(d)))
case 4:
fmt.Printf("part 1: %d\n", day04.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %d\n", day04.Part2(utils.Readfile(d)))
case 5:
fmt.Printf("part 1: %s\n", day05.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %s\n", day05.Part2(utils.Readfile(d)))
case 6:
fmt.Printf("part 1: %d\n", day06.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %d\n", day06.Part2(utils.Readfile(d)))
case 7:
fmt.Printf("part 1: %d\n", day07.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %d\n", day07.Part2(utils.Readfile(d)))
case 8:
fmt.Printf("part 1: %d\n", day08.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %d\n", day08.Part2(utils.Readfile(d)))
case 9:
fmt.Printf("part 1: %d\n", day09.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %d\n", day09.Part2(utils.Readfile(d)))
case 10:
fmt.Printf("part 1: %d\n", day10.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %s\n", day10.Part2(utils.Readfile(d)))
case 11:
fmt.Printf("part 1: %d\n", day11.Part1(utils.Readfile(d)))
fmt.Printf("part 2: %d\n", day11.Part2(utils.Readfile(d)))
default:
panic(fmt.Errorf("no such day: %d", d))
}
}
// Reads day from os.Args.
func day() int {
latest := 10
if len(os.Args) == 1 {
return latest
}
if os.Args[1] == "next" {
genNext(latest + 1)
os.Exit(0)
}
day := utils.MustAtoi(os.Args[1])
return day
}
func genNext(n int) {
os.Mkdir(fmt.Sprintf("day%02d", n), 0755)
f, err := os.Create(fmt.Sprintf("day%02d/day%02d.go", n, n))
utils.PanicOnErr(err)
defer f.Close()
f.WriteString(fmt.Sprintf(`package day%02d
func Part1(input string) int {
return 0
}
func Part2(input string) int {
return 0
}
`, n))
fmt.Printf("wrote day%02d/day%02d.go\n", n, n)
f, err = os.Create(fmt.Sprintf("day%02d/day%02d_test.go", n, n))
utils.PanicOnErr(err)
defer f.Close()
f.WriteString(fmt.Sprintf(`package day%02d
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPart1(t *testing.T) {
r := Part1("")
require.Equal(t, 0, r)
}
func TestPart2(t *testing.T) {
r := Part2("")
require.Equal(t, 0, r)
}
`, n))
fmt.Printf("wrote day%02d/day%02d_test.go\n", n, n)
}

View File

@@ -0,0 +1,74 @@
package grid2d
import (
"strings"
"adventofcode2022/utils"
)
type Grid[T any] struct {
sizeX, sizeY int
matrix [][]T
empty T
}
func NewGrid[T any](sizeX, sizeY int, empty T) *Grid[T] {
matrix := make([][]T, sizeY)
rows := make([]T, sizeX*sizeY)
for i := 0; i < sizeX*sizeY; i++ {
rows[i] = empty
}
j := 0
for i := 0; i < sizeY; i++ {
matrix[i] = rows[j : j+sizeX : j+sizeX]
j += sizeX
}
return &Grid[T]{
sizeX: sizeX,
sizeY: sizeY,
matrix: matrix,
empty: empty,
}
}
func (g *Grid[T]) SizeX() int {
return g.sizeX
}
func (g *Grid[T]) SizeY() int {
return g.sizeY
}
func (g *Grid[T]) Get(x, y int) T {
if x < 0 || x >= g.sizeX {
return g.empty
}
if y < 0 || y >= g.sizeY {
return g.empty
}
return g.matrix[y][x]
}
func (g *Grid[T]) Set(x, y int, v T) {
if x < 0 || x >= g.sizeX {
panic("invalid x")
}
if y < 0 || y >= g.sizeY {
panic("invalid y")
}
g.matrix[y][x] = v
}
func (g *Grid[T]) StringWithFormatter(formatter func(T, int, int) string) string {
var r strings.Builder
for j := 0; j < g.sizeY; j++ {
for i := 0; i < g.sizeX; i++ {
_, err := r.WriteString(formatter(g.matrix[j][i], i, j))
utils.PanicOnErr(err)
}
_, err := r.WriteRune('\n')
utils.PanicOnErr(err)
}
return r.String()
}

View File

@@ -0,0 +1,45 @@
package inputs
import (
"strings"
"adventofcode2022/utils"
"adventofcode2022/utils/grid2d"
sparsegrid "adventofcode2022/utils/sparseGrid"
)
func ToInts(input string, sep string) []int {
var r []int
for _, line := range strings.Split(input, sep) {
if line != "" {
r = append(r, utils.MustAtoi(line))
}
}
return r
}
func ToGrid2D[T any](input, rowSep, colSep string, empty T, conv func(string) T) *grid2d.Grid[T] {
lines := strings.Split(input, rowSep)
grid := grid2d.NewGrid(len(lines[0]), len(lines), empty)
for y, line := range lines {
for x, v := range strings.Split(line, colSep) {
grid.Set(x, y, conv(v))
}
}
return grid
}
func ToSparseGrid[T comparable](input, rowSep, colSep string, empty T, conv func(string) T) *sparsegrid.SparseGrid[T] {
lines := strings.Split(input, rowSep)
grid := sparsegrid.NewGrid(empty)
for y, line := range lines {
for x, v := range strings.Split(line, colSep) {
grid.Set(x, y, conv(v))
}
}
return grid
}

View File

@@ -0,0 +1,81 @@
package sparsegrid
import (
"fmt"
"strings"
"adventofcode2022/utils"
)
type SparseGrid[T comparable] struct {
minX, maxX, minY, maxY int
data map[string]T
empty T
}
func NewGrid[T comparable](empty T) *SparseGrid[T] {
return &SparseGrid[T]{
minX: utils.MaxInt,
maxX: utils.MinInt,
minY: utils.MaxInt,
maxY: utils.MinInt,
data: map[string]T{},
empty: empty,
}
}
func (g *SparseGrid[T]) SizeX() (int, int) {
return g.minX, g.maxX
}
func (g *SparseGrid[T]) SizeY() (int, int) {
return g.minY, g.maxY
}
func (g *SparseGrid[T]) Visited() int {
return len(g.data)
}
func (g *SparseGrid[T]) Get(x, y int) T {
k := key(x, y)
v, ok := g.data[k]
if !ok {
return g.empty
}
return v
}
func (g *SparseGrid[T]) Set(x, y int, v T) {
k := key(x, y)
current, ok := g.data[k]
if ok && v == current {
return
} else if !ok && v == g.empty {
return
} else if v == g.empty {
delete(g.data, k)
} else {
g.data[k] = v
g.minX = utils.Min(g.minX, x)
g.maxX = utils.Max(g.maxX, x)
g.minY = utils.Min(g.minY, y)
g.maxY = utils.Max(g.maxY, y)
}
}
func (g *SparseGrid[T]) StringWithFormatter(formatter func(T, int, int) string) string {
var r strings.Builder
for j := g.minY; j <= g.maxY; j++ {
for i := g.minX; i <= g.maxX; i++ {
_, err := r.WriteString(formatter(g.Get(i, j), i, j))
utils.PanicOnErr(err)
}
_, err := r.WriteRune('\n')
utils.PanicOnErr(err)
}
return r.String()
}
func key(x, y int) string {
return fmt.Sprintf("%d:%d", x, y)
}

207
2022/go/utils/utils.go Normal file
View File

@@ -0,0 +1,207 @@
package utils
import (
"bufio"
"fmt"
"io"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"golang.org/x/exp/constraints"
)
func PanicOnErr(err error) {
if err != nil {
panic(err)
}
}
const MaxInt = int(^uint(0) >> 1)
const MinInt = ^MaxInt
func Max[T constraints.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
func Min[T constraints.Ordered](a, b T) T {
if a < b {
return a
}
return b
}
func SliceMinMax[T constraints.Ordered](slice []T) (*T, *T) {
if len(slice) == 0 {
return nil, nil
}
min := &slice[0]
max := &slice[0]
for i, v := range slice {
if v < *min {
min = &slice[i]
}
if v > *max {
max = &slice[i]
}
}
return min, max
}
func MustAtoi(s string) int {
v, err := strconv.Atoi(s)
PanicOnErr(err)
return v
}
// Returns key from map[T]int which has the max value
func MapFindMax(m interface{}) interface{} {
var maxK interface{} = nil
var maxV = MinInt
iter := reflect.ValueOf(m).MapRange()
for iter.Next() {
k := iter.Key()
v := int(iter.Value().Int())
if v > maxV {
maxV = v
maxK = k.Interface()
}
}
return maxK
}
// Returns key from map[T]int which has the min value
func MapFindMin(m interface{}) interface{} {
var minK interface{} = nil
var minV = MaxInt
iter := reflect.ValueOf(m).MapRange()
for iter.Next() {
k := iter.Key()
v := int(iter.Value().Int())
if v < minV {
minV = v
minK = k.Interface()
}
}
return minK
}
func Readfile(day int) string {
filename := fmt.Sprintf("day%02d/input.txt", day)
file, err := os.Open(filename)
PanicOnErr(err)
defer file.Close()
reader := bufio.NewReader(file)
contents, err := io.ReadAll(reader)
PanicOnErr(err)
return strings.TrimSuffix(string(contents), "\n")
}
func ParseToStruct(re *regexp.Regexp, input string, target interface{}) bool {
m := re.FindStringSubmatch(input)
if m == nil {
return false
}
var useOffset bool
for i, name := range re.SubexpNames() {
if i == 0 {
continue
}
var field reflect.Value
if name == "" {
// use offset
if i == 1 {
useOffset = true
} else if !useOffset {
panic("can't mix named and unnamed subexpressions")
}
field = reflect.ValueOf(target).Elem().Field(i - 1)
} else {
// use name
if i == 1 {
useOffset = false
} else if useOffset {
panic("can't mix named and unnamed subexpressions")
}
field = reflect.ValueOf(target).Elem().FieldByName(name)
}
if field.Kind() == reflect.String {
field.SetString(m[i])
} else if field.Kind() == reflect.Int {
v, err := strconv.Atoi(m[i])
PanicOnErr(err)
field.SetInt(int64(v))
} else if field.Kind() == reflect.Uint8 {
if len(m[i]) != 1 {
panic(fmt.Sprintf("expecting 1 char, got: %s", m[i]))
}
field.SetUint(uint64(m[i][0]))
} else {
panic(fmt.Sprintf("unknown kind: %s", field.Kind()))
}
}
return true
}
func MustParseToStruct(re *regexp.Regexp, input string, target interface{}) {
if !ParseToStruct(re, input, target) {
panic(fmt.Errorf("failed to parse: %s", input))
}
}
func CharToLower(c byte) byte {
return strings.ToLower(string(c))[0]
}
func CharToUpper(c byte) byte {
return strings.ToUpper(string(c))[0]
}
func Contains(haystack []string, needle string) bool {
for _, s := range haystack {
if s == needle {
return true
}
}
return false
}
func Abs[T constraints.Signed](x T) T {
if x < 0 {
return -x
}
return x
}
func Gcd(x, y int) int {
if x <= 0 || y <= 0 {
panic(fmt.Errorf("invalid input: %d, %d", x, y))
}
if x == y {
return x
}
if x > y {
return Gcd(x-y, y)
} else {
return Gcd(x, y-x)
}
}
func Sign[T constraints.Signed](x T) int {
if x < 0 {
return -1
} else if x > 0 {
return 1
} else {
return 0
}
}

8
2023/gareth/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

9
2023/gareth/.idea/awesomeProject.iml generated Normal file
View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

8
2023/gareth/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/awesomeProject.iml" filepath="$PROJECT_DIR$/.idea/awesomeProject.iml" />
</modules>
</component>
</project>

View File

@@ -0,0 +1,61 @@
package day01
import (
"regexp"
"strconv"
"strings"
)
func Part1(input string) int {
total := 0
lines := strings.Split(input, "\r\n")
for _, line := range lines {
regex := regexp.MustCompile("[a-zA-Z]")
numbers := regex.ReplaceAllString(line, "")
number := string(numbers[0]) + string(numbers[len(numbers)-1])
i, _ := strconv.Atoi(number)
total += i
}
return total
}
func Part2(input string) int {
values := map[string]string{
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
}
lines := strings.Split(input, "\r\n")
s := ""
total := 0
for _, line := range lines {
numbers := []string{}
for _, c := range line {
s = s + string(c)
if num, err := strconv.Atoi(string(c)); err == nil {
numbers = append(numbers, strconv.Itoa(num))
s = ""
}
for key, value := range values {
if strings.Contains(s, key) {
numbers = append(numbers, value)
buffer := s[len(s)-1]
s = "" + string(buffer)
}
}
}
number := numbers[0] + numbers[len(numbers)-1]
i, _ := strconv.Atoi(number)
total += i
s = ""
}
return total
}

View File

@@ -0,0 +1,25 @@
package day01
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestPart1(t *testing.T) {
r := Part1(`1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet`)
assert.Equal(t, 142, r)
}
func TestPart2(t *testing.T) {
r := Part2(`two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen`)
assert.Equal(t, 281, r)
}

1000
2023/gareth/day01/input.txt Normal file

File diff suppressed because it is too large Load Diff

14
2023/gareth/go.mod Normal file
View File

@@ -0,0 +1,14 @@
module awesomeProject
go 1.21
require (
github.com/stretchr/testify v1.8.4
golang.org/x/exp v0.0.0-20231127185646-65229373498e
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

12
2023/gareth/go.sum Normal file
View File

@@ -0,0 +1,12 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/exp v0.0.0-20231127185646-65229373498e h1:Gvh4YaCaXNs6dKTlfgismwWZKyjVZXwOPfIyUaqU3No=
golang.org/x/exp v0.0.0-20231127185646-65229373498e/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

12
2023/gareth/main.go Normal file
View File

@@ -0,0 +1,12 @@
package main
import (
"awesomeProject/day01"
"awesomeProject/utils"
"fmt"
)
func main() {
fmt.Printf("part 1: %d\n", day01.Part1(utils.Readfile(01)))
fmt.Printf("part 2: %d\n", day01.Part2(utils.Readfile(01)))
}

View File

@@ -0,0 +1,74 @@
package grid2d
import (
"strings"
"adventofcode2022/utils"
)
type Grid[T any] struct {
sizeX, sizeY int
matrix [][]T
empty T
}
func NewGrid[T any](sizeX, sizeY int, empty T) *Grid[T] {
matrix := make([][]T, sizeY)
rows := make([]T, sizeX*sizeY)
for i := 0; i < sizeX*sizeY; i++ {
rows[i] = empty
}
j := 0
for i := 0; i < sizeY; i++ {
matrix[i] = rows[j : j+sizeX : j+sizeX]
j += sizeX
}
return &Grid[T]{
sizeX: sizeX,
sizeY: sizeY,
matrix: matrix,
empty: empty,
}
}
func (g *Grid[T]) SizeX() int {
return g.sizeX
}
func (g *Grid[T]) SizeY() int {
return g.sizeY
}
func (g *Grid[T]) Get(x, y int) T {
if x < 0 || x >= g.sizeX {
return g.empty
}
if y < 0 || y >= g.sizeY {
return g.empty
}
return g.matrix[y][x]
}
func (g *Grid[T]) Set(x, y int, v T) {
if x < 0 || x >= g.sizeX {
panic("invalid x")
}
if y < 0 || y >= g.sizeY {
panic("invalid y")
}
g.matrix[y][x] = v
}
func (g *Grid[T]) StringWithFormatter(formatter func(T, int, int) string) string {
var r strings.Builder
for j := 0; j < g.sizeY; j++ {
for i := 0; i < g.sizeX; i++ {
_, err := r.WriteString(formatter(g.matrix[j][i], i, j))
utils.PanicOnErr(err)
}
_, err := r.WriteRune('\n')
utils.PanicOnErr(err)
}
return r.String()
}

Some files were not shown because too many files have changed in this diff Show More