How to implement the two sum algorithm to find two values in array that add up to target with Pascal

1 Answer

0 votes
program TwoSumFinder;

uses SysUtils;

type
  TIntArray = array of Integer;

function TwoSum(arr: TIntArray; target: Integer): TIntArray;
var
  i, j: Integer;
begin
  SetLength(TwoSum, 2);
  TwoSum[0] := -1;
  TwoSum[1] := -1;

  for i := 0 to High(arr) do
    for j := i + 1 to High(arr) do
      if arr[i] + arr[j] = target then
      begin
        TwoSum[0] := i;
        TwoSum[1] := j;
        Exit;  // Return immediately when match is found
      end;
end;

procedure PrintResult(arr: TIntArray; target: Integer);
var
  res: TIntArray;
begin
  res := TwoSum(arr, target);
  WriteLn('TwoSum(', target, ') => [', res[0], ', ', res[1], ']');

  if (res[0] <> -1) and (res[1] <> -1) then
    WriteLn('Numbers: ', arr[res[0]], ', ', arr[res[1]]);
end;

var
  array1, array2: TIntArray;
begin
  // Correct array initialization
  SetLength(array1, 6);
  array1[0] := 1; array1[1] := 5; array1[2] := 7;
  array1[3] := 4; array1[4] := 3; array1[5] := 2;

  SetLength(array2, 5);
  array2[0] := 3; array2[1] := 1; array2[2] := 4;
  array2[3] := 2; array2[4] := 5;

  PrintResult(array1, 9);
  PrintResult(array2, 8);
end.


  
(*
run:

TwoSum(9) => [1, 3]
Numbers: 5, 4
TwoSum(8) => [0, 4]
Numbers: 3, 5
  
*)  



 



answered May 22, 2025 by avibootz
...