c# - How do I find the closest array element to an arbitrary (non-member) number? -
seemingly similar questions: "finding closest number in array" (in java) , "find nearest match array of doubles" (actually geography problem).
i have (sorted) array of doubles. given arbitrary number (which may or may not exact match 1 of array elements), how can return index of number closest match?
for example, using following array:
- 1.8
- 2.4
- 2.7
- 3.1
- 4.5
querying 2.5 return index of 1, corresponding value of 2.4.
bonus points detecting values lie outside of range of array elements. example, using array listed above, code may decide 4.6 in, 5.9 out. if want try part of question, specifics in hands.
array.binarysearch
, returns:
the index of specified value in specified array, if value found. if value not found , value less 1 or more elements in array, negative number bitwise complement of index of first element larger value. if value not found , value greater of elements in array, negative number bitwise complement of (the index of last element plus 1).
now won't 100% of way there, since you'll know number either less or greater match, leaves 2 indices check.
Comments
Post a Comment