Reputation: 199
How can I find out the minimum and maximum values of a certain dynamic array defined by array of Integer
?
ex:
Y: array of integer;
Upvotes: 4
Views: 22044
Reputation: 3455
It can be done in a single loop...
function ArrayValRange( somearray: array of integer; var minval: integer; var maxval: integer): boolean;
var
i: integer;
begin
result := false;
if length( somearray) < 1 then
exit;
result := true;
maxval = somearray[ Low(somearray)];
minval = maxval;
for i := Low(somearray)+1 to High(somearray) do
begin
if somearray[i] > maxval then
maxval := somearray[i];
if somearray[i] < minval then
minval := somearray[i];
end;
end;
then
if ArrayValRange( myarray, min, max) then
begin
//do your thing
end;
Upvotes: 3
Reputation: 613282
The easiest way is to use the built-in functions that perform this service. They are called MinIntValue
and MaxIntValue
and can be found in the Math unit.
uses
Math;
....
TheMin := MinIntValue(TheArray);
TheMax := MaxIntValue(TheArray);
Upvotes: 18
Reputation: 380
There are overloaded functions for this in the unit Math:
function MinValue(const Data: array of Single): Single; overload;
function MinValue(const Data: array of Double): Double; overload;
function MinValue(const Data: array of Extended): Extended; overload;
function MinIntValue(const Data: array of Integer): Integer;
function MaxValue(const Data: array of Single): Single; overload;
function MaxValue(const Data: array of Double): Double; overload;
function MaxValue(const Data: array of Extended): Extended; overload;
function MaxIntValue(const Data: array of Integer): Integer;
since you are using integers you should use MinIntValue and MaxIntValue
Upvotes: 11
Reputation: 597111
You have to loop through the array, looking for the desired values, eg:
function TMyClass.GetMinValue: Integer;
var
Idx: Integer;
begin
Result := MyArray[Low(MyArray)];
for Idx := Low(MyArray)+1 to High(MyArray) do
begin
if MyArray[Idx] < Result then
Result := MyArray[Idx];
end;
end;
function TMyClass.GetMaxValue: Integer;
var
Idx: Integer;
begin
Result := MyArray[Low(MyArray)];
for Idx := Low(MyArray)+1 to High(MyArray) do
begin
if MyArray[Idx] > Result then
Result := MyArray[Idx];
end;
end;
Upvotes: 5