From 0378b27aedf31a060c004e5e80fead505e6ab8a4 Mon Sep 17 00:00:00 2001 From: Dory Date: Mon, 4 Dec 2023 09:21:56 -0800 Subject: [PATCH] make part2 clearer --- 04/part2.pl | 40 +++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/04/part2.pl b/04/part2.pl index 1bc2c7c..4e9c10b 100644 --- a/04/part2.pl +++ b/04/part2.pl @@ -1,27 +1,6 @@ :- table match/3. :- table sum/5. -% match1(WinningNums, CardNums, NMatches) -match1(_, [], 0). -match1(Wins, [X|Nums], N) :- member(X, Wins), match1(Wins, Nums, N1), N is N1 + 1. -match1(Wins, [X|Nums], N) :- \+ member(X, Wins), match1(Wins, Nums, N). - -match(Input, Nth, NMatches) :- - nth1(Nth, Input, [Wins|CardNums]), - match1(Wins, CardNums, NMatches). - -% sum(Cards, X, StuffToSum, Indices, Sum). -sum(_, _, [], [0], 0). -sum(Cards, X, [Element|Rest], [I,INext|IRest], Sum) :- - sum(Cards, X, Rest, [INext|IRest], SumOfRest), - Sum is Element + SumOfRest, - I is INext + 1, - match(Cards, I, NMatches_i), NMatches_i >= X - I. -sum(Cards, X, [_|Rest], [I,INext|IRest], SumOfRest) :- - sum(Cards, X, Rest, [INext|IRest], SumOfRest), - I is INext + 1, - match(Cards, I, NMatches_i), NMatches_i < X - I. - % Number of card X = Nx = 1 + sum(Ni*(matches(i) >= x-i), i=1->x-1) ncards([], []). ncards([_|RestOfCards], [Nx|NRest]) :- @@ -30,6 +9,25 @@ ncards([_|RestOfCards], [Nx|NRest]) :- reverse(RestOfCards, ReversedRestOfCards), sum(ReversedRestOfCards, X, NRest, _, Nx_minus_1), Nx is Nx_minus_1 + 1. +% sum(Cards, X, StuffToSum, Indices, Sum). +% This calculates the "sum(Ni*(matches(i) >= x-i), i=1->x-1)" part of Nx +sum(_, _, [], [0], 0). +sum(Cards, X, [Element|Rest], [I,INext|IRest], Sum) :- + sum(Cards, X, Rest, [INext|IRest], SumOfRest), + match(Cards, I, NMatches_i), + I is INext + 1, + (NMatches_i >= X - I -> Sum is Element + SumOfRest; Sum is SumOfRest). + +% match binds the number of matches that card Nth in the list has +match(Cards, Nth, NMatches) :- + nth1(Nth, Cards, [Wins|CardNums]), + match1(Wins, CardNums, NMatches). + +% match1(WinningNums, CardNums, NMatches) binds number of matches for a card. +match1(_, [], 0). +match1(Wins, [X|Nums], M) :- member(X, Wins), match1(Wins, Nums, M1), M is M1 + 1. +match1(Wins, [X|Nums], M) :- \+ member(X, Wins), match1(Wins, Nums, M). + % this is a more normal sum of a list sum([], 0). sum([Element|Rest], Sum) :- sum(Rest, RestOfSum), Sum is Element + RestOfSum.