How to choose minimal subsequence using LINQ?

If I have golf search results:

-3, +5, -3, 0, +1, +8, 0, +6, +2, -8, +5 

I need to find a sequence of three adjacent numbers having a minimal sum. In this example, the subsequence will look like this:

  [-3, +5, -3] [+5, -3, 0] [-3, 0, +1] ... etc ... [+2, -8, +5] 

And the minimum sequence will be [-3, 0, +1] with the sum of -2.

+6
source share
3 answers

You can use this LINQ query:

 int[] golfResult = { -3, +5, -3, 0, +1, +8, 0, +6, +2, -8, +5 }; var combinations = from i in Enumerable.Range(0, golfResult.Length - 2) select new { i1 = golfResult[i], i2 = golfResult[i + 1], i3 = golfResult[i + 2], }; var min = combinations.OrderBy(x => x.i1 + x.i2 + x.i3).First(); int[] minGolfResult = { min.i1, min.i2, min.i3 }; // -3, 0, +1 

Of course, you need to check if there are at least three results in the array.

+5
source

I'm not sure why you will do this with LINQ. I think a direct iterative solution is easier to understand:

 int[] scores = new[] { -3, 5, -3, 0, 1, 8, 0, 6, 2, -8, 5 }; int minimumSubsequence = int.MaxValue; int minimumSubsequenceIndex = -1; for (int i = 0; i < scores.Length - 2; i++) { int sum = scores[i] + scores[i + 1] + scores[i + 2]; if (sum < minimumSubsequence) { minimumSubsequence = sum; minimumSubsequenceIndex = i; } } // minimumSubsequenceIndex is index of the first item in the minimum subsequence // minimumSubsequence is the minimum subsequence sum. 
+2
source

If you really want to do this in LINQ, you can go as follows:

 int length = 3; var scores = new List<int>() { -3, +5, -3, 0, +1, +8, 0, +6, +2, -8, +5 }; var results = scores .Select((value, index) => new { Value = scores.Skip(index - length + 1).Take(length).Sum(), Index = index - length + 1 }) .Skip(length - 1) .OrderBy(x => x.Value) .First() .Index; 

Creates a second list that sums up all previous elements by length , and then sorts it. You

+1
source

All Articles