From 227aa6713d1540093a6613ff749d664c13651373 Mon Sep 17 00:00:00 2001 From: Dory Date: Fri, 15 Dec 2023 00:39:55 -0800 Subject: [PATCH] Make d15p2 a little more readable and remove unneeded imports. --- 15/part1.pl | 1 - 15/part2.pl | 19 +++++++++---------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/15/part1.pl b/15/part1.pl index dcdfe7e..031b7aa 100644 --- a/15/part1.pl +++ b/15/part1.pl @@ -1,5 +1,4 @@ :- use_module(library(pio)). -:- use_module(library(clpfd)). :- initialization(main, main). main([FileName|_]) :- diff --git a/15/part2.pl b/15/part2.pl index 058b87d..01a5a8a 100644 --- a/15/part2.pl +++ b/15/part2.pl @@ -1,20 +1,19 @@ :- 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), + findall(Power, power_of_some_lens(Boxes, Power), Powers), sum_list(Powers, Answer), writef('Answer=%t\n', [Answer]). +power_of_some_lens(Boxes, Power) :- + nth1(BoxI, Boxes, _-Box), + nth1(LensI, Box, _-Focal), + Power is BoxI * LensI * Focal. + perform_all(Actions, FinalBoxes) :- length(EmptyBoxes, 256), foldl([N-[], N, NextN]>>(NextN is N + 1), EmptyBoxes, 0, _), @@ -29,10 +28,10 @@ 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). +add(Focal, Label, Box, NewBox) :- select(Label-_, Box, Label-Focal, NewBox), !. +add(Focal, Label, Box, NewBox) :- append(Box, [Label-Focal], NewBox). -% Input stuff. [0-(add-1)-"rn", 3-remove-"cm", ...] +% Input stuff. [0-add(5)-"rn", 3-remove-"cm", ...] input(Name, Actions) :- phrase_from_file(insts(Actions), Name). insts([]) --> (eos; "\n"), !.