Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding closest value in an array

Tags:

arrays

c#

find

int[] array = new int[5]{5,7,8,15,20};  int TargetNumber = 13; 

For a target number, I want to find the closest number in an array. For example, when the target number is 13, the closest number to it in the array above is 15. How would I accomplish that programmatically in C#?

like image 402
user1328639 Avatar asked Apr 12 '12 09:04

user1328639


People also ask

How do I find the closest number in an array in C?

So if the array is like [2, 5, 6, 7, 8, 8, 9] and the target number is 4, then closest element is 5. We can solve this by traversing through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolute difference.


1 Answers

EDIT: Have adjusted the queries below to convert to using long arithmetic, so that we avoid overflow issues.

I would probably use MoreLINQ's MinBy method:

var nearest = array.MinBy(x => Math.Abs((long) x - targetNumber)); 

Or you could just use:

var nearest = array.OrderBy(x => Math.Abs((long) x - targetNumber)).First(); 

... but that will sort the whole collection, which you really don't need. It won't make much difference for a small array, admittedly... but it just doesn't feel quite right, compared with describing what you're actually trying to do: find the element with the minimum value according to some function.

Note that both of these will fail if the array is empty, so you should check for that first.

like image 133
Jon Skeet Avatar answered Sep 22 '22 05:09

Jon Skeet