Question

hi i need to find the biggest dense region in a List of values based on a given range

example:

var radius =5; //Therm edited
var list = new List<int>{0,1,2,3,4,5,12,15,16,22,23,24,26,27,28,29};

//the following dense regions exist in the list above
var region1 = new List<int> { 0, 1, 2, 3, 4, 5 };           // exist 6 times (0, 1, 2, 3, 4, 5)
var region2 = new List<int> { 12, 15, 16};                  // exist 3 times (12, 15, 16)
var region3 = new List<int> { 22, 23, 24, 26, 27};          // exist 1 times (22)
var region4 = new List<int> { 22, 23, 24, 26, 27, 28};      // exist 1 times (23)
var region5 = new List<int> { 22, 23, 24, 26, 27, 28, 29 }; // exist 3 times (24, 26, 27)
var region6 = new List<int> { 23, 24, 26, 27, 28, 29 };     // exist 1 times (28)
var region7 = new List<int> { 24, 26, 27, 28, 29 };         // exist 1 times (29)

//var result{22,23,24,26,27,28,29}

the solution doesn't really need to be fast because the max number of values is 21 is there an way to use fluent to achieve this?

i only know how to get the closest value

int closest = list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-number) ? x : y);

and how to get values between 2 numbers

var between = list.Where(value=> min < value && value < max);

Edit

additional information's

Ok range is maybe the wrong therm radius would be a better word.

I define the dense region as the largest count of all values between currenvalue-range and currenvalue + range we get the dense region

Was it helpful?

Solution

A rather cryptic (but short) way would be:

int w = 5; // window size
var list = new List<int> { 0, 1, 2, 3, 4, 5, 12, 15, 16, 22, 
                           23, 24, 26, 27, 28, 29 };

var result = list.Select(x => list.Where(y => y >= x - w && y <= x + w))
                 .Aggregate((a, b) => (a.Count() > b.Count()) ? a : b);

Console.WriteLine(string.Join(",", result.ToArray()));

Prints

22,23,24,26,27,28,29

This code consists of 3 steps:

  • For a given x the snippet list.Where(y => y >= x - w && y <= x + w) gives all elements from the list that are in the cluster around x.
  • list.Select(x => ...) computes that cluster for every element of the list.
  • .Aggregate((a, b) => (a.Count() > b.Count()) ? a : b) takes the cluster of maximum size.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top