Added solution for "Day 9: Mirage Maintenance", part 2

This commit is contained in:
Stefan Müller 2023-12-09 23:11:37 +01:00 committed by Stefan Müller
parent f69d60e5db
commit 09baefc881
2 changed files with 35 additions and 9 deletions

View File

@ -31,7 +31,7 @@ type
TMirageMaintenance = class(TSolver)
private
FN: Integer;
FLagrangePolynomialsInN: specialize TList<Int64>;
FLagrangePolynomialsInN, FLagrangePolynomialsInMinusOne: specialize TList<Int64>;
procedure CalcLagrangePolynomials;
public
constructor Create;
@ -48,19 +48,23 @@ implementation
procedure TMirageMaintenance.CalcLagrangePolynomials;
var
sign, i, j: Integer;
sign1, sign2, i, j: Integer;
begin
FLagrangePolynomialsInN.Clear;
FLagrangePolynomialsInMinusOne.Clear;
if FN mod 2 = 0 then
sign := -1
sign1 := -1
else
sign := 1;
sign1 := 1;
sign2 := 1;
// Calculates the polynomials in N and -1.
for i := 0 to FN - 1 do
begin
FLagrangePolynomialsInN.Add(sign);
sign := -sign;
FLagrangePolynomialsInN.Add(sign1);
sign1 := -sign1;
FLagrangePolynomialsInMinusOne.Add(sign2);
sign2 := -sign2;
if i < FN - FN div 2 then
begin
@ -81,18 +85,38 @@ begin
for j := 2 to FN - i - 1 do
FLagrangePolynomialsInN[i] := FLagrangePolynomialsInN[i] div j;
end;
if i < FN div 2 then
begin
// Multiplies by the non-cancelled numerator terms.
for j := FN - i to FN do
FLagrangePolynomialsInMinusOne[i] := FLagrangePolynomialsInMinusOne[i] * j;
// Divides by the non-cancelled denominator terms.
for j := 2 to i + 1 do
FLagrangePolynomialsInMinusOne[i] := FLagrangePolynomialsInMinusOne[i] div j;
end
else begin
// Multiplies by the non-cancelled numerator terms.
for j := i + 2 to FN do
FLagrangePolynomialsInMinusOne[i] := FLagrangePolynomialsInMinusOne[i] * j;
// Divides by the non-cancelled denominator terms.
for j := 2 to FN - i - 1 do
FLagrangePolynomialsInMinusOne[i] := FLagrangePolynomialsInMinusOne[i] div j;
end;
end;
end;
constructor TMirageMaintenance.Create;
begin
FLagrangePolynomialsInN := specialize TList<Int64>.Create;
FLagrangePolynomialsInMinusOne := specialize TList<Int64>.Create;
FN := 0;
end;
destructor TMirageMaintenance.Destroy;
begin
FLagrangePolynomialsInN.Free;
FLagrangePolynomialsInMinusOne.Free;
inherited Destroy;
end;
@ -114,6 +138,8 @@ begin
y := StrToInt(split[i]);
p := y * FLagrangePolynomialsInN[i];
Inc(FPart1, p);
p := y * FLagrangePolynomialsInMinusOne[i];
Inc(FPart2, p);
end;
end;

View File

@ -62,7 +62,7 @@ end;
procedure TMirageMaintenanceFullDataTestCase.TestPart2;
begin
AssertEquals(-1, FSolver.GetResultPart2);
AssertEquals(1108, FSolver.GetResultPart2);
end;
{ TMirageMaintenanceExampleTestCase }
@ -79,7 +79,7 @@ end;
procedure TMirageMaintenanceExampleTestCase.TestPart2;
begin
AssertEquals(-1, FSolver.GetResultPart2);
AssertEquals(2, FSolver.GetResultPart2);
end;
initialization