Linq Expression Slow - Optimization Needed, If Possible

I have a list of integers "numberRangeList" containing 31 integers from 62 to 92 in sequential order, I am extracting a second list of integers "extractList" that will contain 10 integers, the sum of which is equal to "total". The problem is that it takes about 30 seconds to calculate, is there a way to speed this up?

        var numberRangeList = new List<int>() { 62, 63, ...92 };
        var total = 772;
        var extractedList= (from n1 in numberRangeList
                      from n2 in numberRangeList
                      from n3 in numberRangeList
                      from n4 in numberRangeList
                      from n5 in numberRangeList
                      from n6 in numberRangeList
                      from n7 in numberRangeList
                      from n8 in numberRangeList
                      from n9 in numberRangeList
                      from n10 in numberRangeList
                      where n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9 + n10 == total
                      select new List<int> { n1, n2, n3, n4, n5, n6, n7, n8, n9, n10 }).Take(1).First();
+4
source share
3 answers

, 10 , . (, , -.) . , , 30 .

, . , , , .

:. @Saverio Terracciano, Knapsack , . , .

+1

The problem is not LINQ query - the problem is that your complexity of the O (n ^ 10) algorithm is performed approximately (92-62 + 1) ^ 10 operations - which is a lot of work even for a modern processor, you can solve your problem using the algorithm Knapsack dynamic programming and then use BFS (Width Search) to find a result that contains ten numbers.

+1
source

Source: https://habr.com/ru/post/1545471/


All Articles