Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the closest array element to an arbitrary (non-member) number?

Seemingly similar questions: "Finding closest number in an array" (in Java) and "find nearest match to array of doubles" (actually a geography problem).

I have a (sorted) array of doubles. Given an arbitrary number (which may or may not be an exact match for one of the array elements), how can I return the index of the number which is the closest match?

For example, using the following array:

  • 1.8
  • 2.4
  • 2.7
  • 3.1
  • 4.5

Querying 2.5 would return with an index of 1, corresponding to the value of 2.4.

Bonus points for detecting values that lie completely outside of the range of the array elements. For example, using the array listed above, your code may decide that 4.6 is in, but 5.9 is out. If you want to try this part of the question, the specifics are in your hands.

like image 461
Tom Wright Avatar asked Nov 16 '10 11:11

Tom Wright


1 Answers

Array.BinarySearch, which returns:

The index of the specified value in the specified array, if value is found. If value is not found and value is less than one or more elements in array, a negative number which is the bitwise complement of the index of the first element that is larger than value. If value is not found and value is greater than any of the elements in array, a negative number which is the bitwise complement of (the index of the last element plus 1).

Now that won't get you 100% of the way there, since you'll know the number is either less than or greater than the match, but it really only leaves you with two indices to check.

like image 134
Mark Rushakoff Avatar answered Sep 28 '22 00:09

Mark Rushakoff