Matthew Goulart Matthew Goulart - 1 year ago 52 Question

What is the least expensive way to find the two closest numbers surrounding a given value in a list of numbers?

Say we have a list of numbers:


and a single value :

What is the least expensive way to find the closest 2 numbers surrounding the value in the list. So in our example, the answer would be

Currently, I am using a loop to make 2 lists, one of numbers above and one of numbers below. Then I use something like this:

point1 = pointsAbove.Aggregate(Function(x, y) If(Math.Abs(x.X - xVal) < Math.Abs(y.X - xVal), x, y))
point2 = pointsBelow.Aggregate(Function(x, y) If(Math.Abs(x.X - xVal) < Math.Abs(y.X - xVal), x, y))

This seems so clunky to me. So I look to you!

Answer Source

Try the code below:

List<int> numbers = new List<int>(){ 6, 7, 8, 9, 1, 2, 3, 4, 5 };
int middle = 6;

var min = numbers.Where(y => y < middle).Max(); // min = 5
var max = numbers.Where(y => y > middle).Min(); // max = 7

The code above will work fine for sorted and unsorted lists.

If you can't be certain that you have at least one min and/or one max value, you must do this, otherwise you'll get an Exception:

var min = numbers.Where(y => y < middle).DefaultIfEmpty().Max(); 
var max = numbers.Where(y => y > middle).DefaultIfEmpty().Min();

And, in the case you are sure 100% of the time that the list is sorted, you can save a bit of performance doing the code below:

var min = numbers.LastOrDefault(y => y < middle); 
var max = numbers.FirstOrDefault(y => y > middle);

I hope it helped you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download