T
T
ToKoMoK2019-09-09 22:39:48
C++ / C#
ToKoMoK, 2019-09-09 22:39:48

LINQ, How to decompose a list into three maximally equal lists?

Initial data - a list of arbitrary length
L123 list (1, 5, 7, 3, 2, 9, 1)
Goal - decompose as evenly as possible into three lists
L1, L2, L3
Algorithm
Sort L123 in descending order L123 list (9 ,7, 5, 3, 2, 1, 1)
We look for the sum L1, L2, L3 and add the first element L123 to any minimal list, and so on.
Outcome L1(9); L2(7, 2); L3(5, 3, 1, 1)
How to implement this in LINQ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ToKoMoK, 2019-09-10
@ToKoMoK

Thank you. to everyone who was interested.
Decided everything myself)

List<List<double>> L123 = new List<List<double>> { new List<double>(), new List<double>(), new List<double>() };
            new List<double>() { 1, 1, 2, 3, 5, 7, 9 }
               .OrderByDescending(a => a)
               .ToList()
               .ForEach(b =>
               {
                   L123
                  .ElementAt(L123
                            .Select((e, i) => new { e, i })
                            .Aggregate((f, s) => f.e.Sum() < s.e.Sum() ? f : s)
                            .i)
                  .Add(b);
               });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question