Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance between two values

Tags:

c#

linq

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();
like image 205
Impostor Avatar asked Feb 07 '23 22:02

Impostor


1 Answers

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.

like image 149
juharr Avatar answered Feb 20 '23 01:02

juharr