Reputation: 27
I have a problem: Is there any way I can find the minimum value of an Array that is not 0? Let's say I have this Array:
{0,2,0,0,1} and I want it to find 1.
Upvotes: 0
Views: 132
Reputation: 881573
It should just be a slight variation on finding the minimum including zero. This would be achieved by setting the minimum to the first value and then going through all the others, replacing the minimum if a value in the array is lower.
The modification needed to that for your scenario is to just ignore those having a value of zero. Something like this should do:
var numbers:Array = [0,2,0,0,1];
var started:Boolean = false;
var minval:Number = 0;
for each (var num:Number in numbers) {
if ((!started) && (num != 0)) {
started = true;
minval = num;
}
if ((started) && (num != 0) && (num < minval)) {
minval = num;
}
}
The first if
statement will be the only one executed until you find the first non-zero value, at which point you'll set started
and store that number as the minimum.
From then on (including on that iteration), you'll just check the non-zero numbers to see if they're less and store them if so.
At the end, either started
will be false
in which case there were no non-zero numbers, or started
will be true
and minval
will hold the smallest number found.
Upvotes: 1