Jump to content

Two sum: Difference between revisions

m
→‎{{header|Pascal}}: checking High(A) was the most time consuming in function Check2SumUnSorted
(added =={{header|Pascal}}==)
m (→‎{{header|Pascal}}: checking High(A) was the most time consuming in function Check2SumUnSorted)
Line 54:
<pre>[1,3]</pre>
=={{header|Pascal}}==
A little bit lengthy. Implemented an unsorted Version with quadratic runtime too and an extra test case with 60000 elements that needs 2999959999*3000059998/2 ~ 4501.8 miobillion checks ( ~2 cpu-cycles/check summations).
<lang pascal>
program twosum;{$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
{$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
 
uses
sysutils;
Line 68 ⟶ 66:
tMyArray = array of NativeInt;
const
// just a gag using unusual index limits
ConstArray :array[-17..-13] of NativeInt = (0, 2, 11, 19, 90);
Line 73 ⟶ 72:
sum:NativeInt;
var Sol:tSolRec):boolean;
//Check every possible sum A[0max] + A[max-1..Max0] than A[1] + A[2..Max]...
//than A[max-1] + A[max-2..0] etc pp.
//quadratic runtime: maximal (max-1)*max/ 2 checks
//High(A) always checked for dynamic array, even const
//therefore run High(A) to low(A) = is always 0 for dynamic array
var
i,j,tmpSum: NativeInt;
Line 80 ⟶ 82:
Sol.SolRecI:=0;
Sol.SolRecJ:=0;
i := lowHigh(A);
while i <> Highlow(A) do
Begin
tmpSum := Sumsum-a[i];
j := i+-1;
while( j <>= Highlow(A)) do
begin
if tmpSum = a[j] then
Begin
Sol.SolRecI:=ij;Sol.SolRecJ:=ji;
result := true;
EXIT;
end;
incdec(j);
end;
incdec(i);
end;
result := false;
Line 127 ⟶ 129:
dec(j);
end;
writeln(i:10,j:10);
result := false;
end;
Line 138 ⟶ 141:
randomize;
setlength(CheckArr,High(ConstArray)-Low(ConstArray)+1);
For i := 0High(CheckArr) todownto SizeOflow(ConstArrayCheckArr)-1 do
CheckArr[i] := ConstArray[i+low(ConstArray)];
 
Line 148 ⟶ 151:
//now test a bigger sorted array..
setlength(CheckArr,3000060000);
For i := High(CheckArr) downto 0 do
CheckArr[i] := 0i;
MySum := CheckArr[HighLow(CheckArr)-1] := +CheckArr[Low(CheckArr)+1];
writeln(#13#10,'Now checking array of ',length(CheckArr),
CheckArr[High(CheckArr)] := 2;
' elements',#13#10);
//runtime about 1 second
MySum := 3;
//runtime 1 second
IF Check2SumUnSorted(CheckArr,MySum,Sol) then
writeln('[',Sol.SolRecI,',',Sol.SolRecJ,'] sum to ',MySum)
Line 166 ⟶ 168:
else
writeln('No solution found');
end.</lang>
</lang>
{{out}}
<pre>[1,3] sum to 21
[29998,29999] sum to 3
[29998,29999] sum to 3
 
Now checking array of 60000 elements
real 0m1.097s</pre>
 
[299980,299991] sum to 31
[299980,299991] sum to 31
 
real 0m1.097s</pre>035s
</langpre>
 
=={{header|REXX}}==
<lang rexx>list=0 2 11 19 90
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.