Let's say I have an Array of numbers: [2,3,3,4,2,2,5,6,7,2]
What is the best way to find the minimum or maximum value in that Array?
Right now, to get the maximum, I am looping through the Array, and resetting a variable to the value if it is greater than the existing value:
var myArray:Array /* of Number */ = [2,3,3,4,2,2,5,6,7,2]; var maxValue:Number = 0; for each (var num:Number in myArray) { if (num > maxValue) maxValue = num; }
This just doesn't seem like the best performing way to do this (I try to avoid loops whenever possible).
M = min( A ) returns the minimum elements of an array. If A is a vector, then min(A) returns the minimum of A . If A is a matrix, then min(A) is a row vector containing the minimum value of each column of A .
Using min_element() with max_element() function C++ standard library also provides individual functions min_element() and max_element() to find smallest and largest elements in array, respectively. That's all about finding the minimum and maximum values in an array in C++.
The theoretical answers from everyone else are all neat, but let's be pragmatic. ActionScript provides the tools you need so that you don't even have to write a loop in this case!
First, note that Math.min()
and Math.max()
can take any number of arguments. Also, it's important to understand the apply()
method available to Function
objects. It allows you to pass arguments to the function using an Array
. Let's take advantage of both:
var myArray:Array = [2,3,3,4,2,2,5,6,7,2]; var maxValue:Number = Math.max.apply(null, myArray); var minValue:Number = Math.min.apply(null, myArray);
Here's the best part: the "loop" is actually run using native code (inside Flash Player), so it's faster than searching for the minimum or maximum value using a pure ActionScript loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With