Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the Minimum Positive Value

What's the best algorithm to find the smallest non zero positive value from a fixed number (in this case 3) of values or return 0 if there are no positive questions?

My naive approach is below (in Delphi, but feel free to use whatever you like), but I think there's a more elegant way.

value1Temp := MaxInt;
value2Temp := MaxInt;
value3Temp := MaxInt;

if ( value1T > 0) then
  value1Temp := value1;
if ( value2 > 0) then
  value2Temp := value2;
if ( value3 > 0) then
  value3Temp  := value3;

Result := Min(value1Temp, Min(value2Temp, value3Temp));
if Result = MaxInt then
  Result := 0;

Edit: Sorry added what's needed if there are no positive numbers. I thought I had it in there before, but must have missed it.

like image 993
Ray Avatar asked Dec 18 '08 01:12

Ray


People also ask

What is the formula to find minimum?

You can find this minimum value by graphing the function or by using one of the two equations. If you have the equation in the form of y = ax^2 + bx + c, then you can find the minimum value using the equation min = c - b^2/4a.

How do you find the minimum value other than zero?

Find minimum value excluding zero with formula Please apply the following formula to get the minimum value in that range excluding zero in Excel. 1. Select a blank cell (H1) for placing the minimum value, enter formula =SMALL(A1:E7,COUNTIF($A$1:$E$7,0)+1) into the Formula Bar, and then press the Enter key.

What is the lowest number above 0?

No, there is not “a smallest real number greater than zero” nor “a greatest real number smaller than zero”. Let's say you think you have found the least real number greater than 0, and we will call it s. It does not matter whether you guessed it, used some algorithm to determine it, or how you found it.


1 Answers

How about the following function (in Delphi of course):

function LowestPositiveInt(IntArr : array of Integer):Integer;
var
  iX : integer;
  bValid : boolean;
begin
  Result := MaxInt;
  bValid := False;
  for ix := 0 to High(IntArr) do
    if (IntArr[ix] > 0) then
      begin
        bValid := true;
        if (IntArr[iX] < Result) then
          Result := IntArr[ix];
      end;
  if not bValid then
    Result := 0;
end;

then call it like the following:

ShowMessage(IntToStr( LowestPositiveInt([5,2,3,-1,12]) ));

This should return 2. The advantage of this approach is that the array can take any number of items, including integer variables...so using your example above you could say:

Result := LowestPositiveInt( [ Value1, Value2, Value3 ] );

EDIT Updated to handle the LowestPosititiveInt( [ MaxInt, MaxInt, MaxInt ] ) scenario.

like image 90
skamradt Avatar answered Sep 22 '22 21:09

skamradt