I have a array
int[] Values = new int[] { 5, 43, 45, 25, 16, 89, 65, 36, 62 };
and currently i am calculating the maximum distance between all values 84 = 89 - 5
int MaxDistance = Values.SelectMany((a) => Values.Select((b) => Math.Abs(a - b))).Max();
now I want to calculate the minimum distance 2 = 45 - 43
@ycsun's commment - this doesn't work
int MinDistancee = Values.SelectMany((ia, a) => Values.Select((ib, b) => ib == ia ? int.MaxValue : Math.Abs(a - b))).Min();
Try this instead
int MinDistance = Values.SelectMany(
(a, i) => Values.Skip(i + 1).Select((b) => Math.Abs(a - b))).Min();
This makes sure you don't calculate the difference between numbers at the same index or a set of numbers at different indexes twice. Basically this uses the overload of SelectMany
that includes the index, then you just want to do your difference with all the numbers after the current index by using Skip
.
It should be noted that a solution using for
loops in the form of
for(int i = 0; i < Values.Length - 1; i++)
for(int j = i + 1; j < Values.Length; j++)
would be more performant though.
One caveat here though is if you have negative numbers. Then there will be a difference between the absolute value of a-b
versus b-a
. In that case you'd want to sort the list first to make sure the difference always has a
as the larger number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With