Added solution for "Day 6: Wait For It", part 2

This commit is contained in:
Stefan Müller 2023-12-06 12:45:23 +01:00 committed by Stefan Müller
parent 93f6ceb1db
commit 2af4cf78b5
2 changed files with 32 additions and 13 deletions

View File

@ -30,6 +30,8 @@ type
TWaitForIt = class(TSolver)
FTimes, FDistances: specialize TFPGList<Cardinal>;
FLongTime, FLongDistance: UInt64;
function CalcRange(const ATime, ADistance: UInt64): Cardinal;
public
constructor Create;
destructor Destroy; override;
@ -43,6 +45,18 @@ implementation
{ TWaitForIt }
function TWaitForIt.CalcRange(const ATime, ADistance: UInt64): Cardinal;
var
x1, x2: Integer;
p, s: Double;
begin
p := ATime / 2;
s := Sqrt(p * p - ADistance);
x1 := Math.Floor(p - s + 1);
x2 := Math.Ceil(p + s - 1);
Result := x2 - x1 + 1;
end;
constructor TWaitForIt.Create;
begin
FTimes := specialize TFPGList<Cardinal>.Create;
@ -60,37 +74,42 @@ procedure TWaitForIt.ProcessDataLine(const ALine: string);
var
split: TStringArray;
list: specialize TFPGList<Cardinal>;
value: PUInt64;
i: Integer;
cleaned: string;
begin
split := ALine.Split([' ', ':']);
if split[0] = 'Time' then
list := FTimes
begin
list := FTimes;
value := @FLongTime;
end
else if split[0] = 'Distance' then
list := FDistances
begin
list := FDistances;
value := @FLongDistance;
end
else
Exit;
cleaned := '';
for i := 1 to Length(split) - 1 do
if split[i] <> '' then
begin
list.Add(StrToDWord(split[i]));
cleaned := Concat(cleaned, split[i]);
end;
value^ := StrToUInt64(cleaned);
end;
procedure TWaitForIt.Finish;
var
i, x1, x2: Integer;
p, s: Double;
i: Integer;
begin
FPart1 := 1;
for i := 0 to FTimes.Count - 1 do
begin
p := FTimes[i] / 2;
s := Sqrt(p * p - FDistances[i]);
x1 := Math.Floor(p - s + 1);
x2 := Math.Ceil(p + s - 1);
FPart1 := FPart1 * (x2 - x1 + 1);
end;
FPart1 := FPart1 * CalcRange(FTimes[i], FDistances[i]);
FPart2 := CalcRange(FLongTime, FLongDistance);
end;
function TWaitForIt.GetDataFileName: string;

View File

@ -62,7 +62,7 @@ end;
procedure TWaitForItFullDataTestCase.TestPart2;
begin
AssertEquals(-1, FSolver.GetResultPart2);
AssertEquals(30077773, FSolver.GetResultPart2);
end;
{ TWaitForItExampleTestCase }
@ -79,7 +79,7 @@ end;
procedure TWaitForItExampleTestCase.TestPart2;
begin
AssertEquals(-1, FSolver.GetResultPart2);
AssertEquals(71503, FSolver.GetResultPart2);
end;
initialization