views:

63

answers:

2

What is the best way to find the closes value in a range...

for example i have an array with 0, 90, 180, 270, 360.. And a number 46...

What is the best way to find 90 in the array?

(in actipnscript 3)

+2  A: 

How do you want to define closest?

If you mean the least difference, then loop through each value, compute the absolute value of the difference, keep note of the smallest value seen.

If the list is sorted by magnitude, then stop when you see a difference that's greater than the smallest found, esle loop through the entire set.

Mitch Wheat
+1. if the array doesn't change to often, you should try keeping it sorted and go with the second approach.
back2dos
+1  A: 

If your array match exactly your pattern example ([0, 90, 180, 270, 360]), it seems to be angles separated by a step of 90, then you can do:

var range:Array=[0, 90, 180, 270, 360];

function getIndexFrom(value:Number):int {

 // keep the value in range (0, 360)
 if (value<0) {
   value= 360 - (-value % 360);
 } else if (value>360) {
  value=value % 360;
 }

 return int(0.5 + ( value / 90.0 ) );
}
Patrick