{ Solutions to the Advent Of Code. Copyright (C) 2023 Stefan Müller This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . } unit UTrebuchet; {$mode ObjFPC}{$H+} interface uses Classes, SysUtils; type { TTrebuchet } TTrebuchet = class(TObject) private FValue: Integer; procedure RunSolution; procedure ProcessDataLine(const ALine: string); function FindFirstDigit(const ALine: string; out OEndIndex: Integer): Integer; function FindLastDigit(const ALine: string; const AFirstDigit, AFirstDigitEndIndex: Integer): Integer; function CheckDigit(const ALine: string; const AIndex: Integer; out ODigit, OEndIndex: Integer): Boolean; public constructor Create; class procedure Solve; static; end; implementation { TTrebuchet } procedure TTrebuchet.RunSolution; var data: TextFile; s: string; begin AssignFile(data, ConcatPaths(['data', 'trebuchet_calibration_document.txt'])); try reset(data); while (not EOF(data)) do begin readln(data, s); ProcessDataLine(s); end; finally CloseFile(data) end; WriteLn('Part 1: ', FValue); end; procedure TTrebuchet.ProcessDataLine(const ALine: string); var first, endIndex, last: Integer; begin first := FindFirstDigit(ALine, endIndex); last := FindLastDigit(ALine, first, endIndex); Inc(FValue, first * 10 + last); end; function TTrebuchet.FindFirstDigit(const ALine: string; out OEndIndex: Integer): Integer; var i: Integer; begin for i := 1 to ALine.Length do if CheckDigit(ALine, i, Result, OEndIndex) then Exit; end; function TTrebuchet.FindLastDigit(const ALine: string; const AFirstDigit, AFirstDigitEndIndex: Integer): Integer; var i, endIndex: Integer; begin for i := ALine.Length downto AFirstDigitEndIndex + 1 do if CheckDigit(ALine, i, Result, endIndex) then Exit; // Returns the first digit if no digit was found after the end index of the first digit. Result := AFirstDigit; end; function TTrebuchet.CheckDigit(const ALine: string; const AIndex: Integer; out ODigit, OEndIndex: Integer): Boolean; begin if ALine[AIndex] in ['0'..'9'] then begin ODigit := StrToInt(ALine[AIndex]); OEndIndex := AIndex; Result := true; end else begin ODigit := -1; OEndIndex := -1; Result := false; end; end; constructor TTrebuchet.Create; begin FValue := 0; end; class procedure TTrebuchet.Solve; var trebuchet: TTrebuchet; begin WriteLn('--- Day 1: Trebuchet?! ---'); trebuchet := TTrebuchet.Create; trebuchet.RunSolution; trebuchet.Free; end; end.