[Solved] Find furthest and closest number to a number in array c# [closed]


If you can use List<int> instead of array it makes things easier to code and probably cleaner depending on who you ask.

let say you change this :

int[] array = new int[10] {g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};

Into a list like this :

List<int> values = new List<int>(){g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};

An aggregate will test each elements until the list has been completely tested.
So we can try get the closest and furthest value like so

// value you want to check is the average of the list.
// Average is already implemented for the List
var value = values.Average();

// will keep the closest value in the collection to our value we are looking for
// and keep testing with the following value to end up with the final closest
var closestTo = values.Aggregate((x, y) => Math.Abs(x - value) < Math.Abs(y - value) ? x : y);

// same logic as closest except we keep the furthest
var furthestTo = values.Aggregate((x, y) => Math.Abs(x - value) > Math.Abs(y - value) ? x : y); 

1

solved Find furthest and closest number to a number in array c# [closed]