This commit is contained in:
Dory 2023-12-15 00:17:21 -08:00
parent 0f5dcc20ce
commit 8683c9c8b3
4 changed files with 77 additions and 0 deletions

1
15/input.txt Normal file

File diff suppressed because one or more lines are too long

27
15/part1.pl Normal file
View File

@ -0,0 +1,27 @@
:- use_module(library(pio)).
:- use_module(library(clpfd)).
:- initialization(main, main).
main([FileName|_]) :-
input(FileName, Input),
hashes(Input, Hash),
writef('Answer=%t\n', [Hash]).
hashes(Strs, Hash) :-
concurrent_maplist(reverse, Strs, RStrs),
concurrent_maplist(hash, RStrs, Hashes),
sum_list(Hashes, Hash).
hash([], 0).
hash([C|Str], Hash) :- hash(Str, Prev), Hash is (Prev + C)*17 mod 256.
% Input stuff
input(FileName, Input) :- phrase_from_file(string(Input), FileName).
string([]) --> (eos; "\n"), !.
string([Item|Items]) --> item(Item), string(Items).
item([]) --> (","; "\n"; eos), !.
item([C|Chars]) --> [C], item(Chars).
eos([], []).

48
15/part2.pl Normal file
View File

@ -0,0 +1,48 @@
:- use_module(library(pio)).
:- use_module(library(dcg/basics)).
:- use_module(library(clpfd)).
:- initialization(main, main).
main([FileName|_]) :-
input(FileName, Actions),
perform_all(Actions, Boxes),
findall(
Power,
( nth1(BoxI, Boxes, _-Box),
nth1(LensI, Box, _-Focal),
Power is BoxI * LensI * Focal),
Powers),
sum_list(Powers, Answer),
writef('Answer=%t\n', [Answer]).
perform_all(Actions, FinalBoxes) :-
length(EmptyBoxes, 256),
foldl([N-[], N, NextN]>>(NextN is N + 1), EmptyBoxes, 0, _),
foldl(perform, Actions, EmptyBoxes, FinalBoxes).
perform(BoxN-Action-Label, Before, After) :-
nth0(BoxN, Before, BoxN-Box),
call(Action, Label, Box, NewBox),
select(BoxN-Box, Before, BoxN-NewBox, After).
remove(_, [], []).
remove(Label, [Label-_|Box], Box) :- !.
remove(Label, [Lens|Box], [Lens|NewBox]) :- remove(Label, Box, NewBox).
add(F, Label, OldBox, NewBox) :- select(Label-_, OldBox, Label-F, NewBox), !.
add(F, Label, OldBox, NewBox) :- append(OldBox, [Label-F], NewBox).
% Input stuff. [0-(add-1)-"rn", 3-remove-"cm", ...]
input(Name, Actions) :- phrase_from_file(insts(Actions), Name).
insts([]) --> (eos; "\n"), !.
insts([Box-Action-LabelS|Items]) -->
item(Label-Action), insts(Items),
{reverse(Label, Rev), hash(Rev, Box), string_codes(LabelS, Label)}.
item([]-remove) --> "-", (","; "\n"; eos), !.
item([]-add(N)) --> "=", number(N), (","; "\n"; eos), !.
item([C|Chars]-X) --> [C], item(Chars-X).
hash([], 0).
hash([C|Str], Hash) :- hash(Str, Prev), Hash is (Prev + C)*17 mod 256.

1
15/test.txt Normal file
View File

@ -0,0 +1 @@
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7