Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all combinations of several List<int> [duplicate]

Tags:

c#

Differs from sugested solution above in that a list item can only appear once for each row.

This is for a booking system for my spa. Different employees can perform different treatments.

I have a List<List<int>>. These are therapists that can perform the treatment that is booked.

Each list (booking) contain a number of integers like this (these are therapists that can perform the booking):

{1, 3, 6},  //Booking 1
{1, 2, 6},  //Booking 2
{1},        //Booking 3
{2,3}       //Booking 4

I'd like to see all possible combinations where the number can only appear in one Place. For the above list the two possible ombinations would be:

6,2,1,3 or 3,6,1,2

That is for the first combination:

  • Booking 1: Therapist 6
  • Booking 2: Therapist 2
  • Booking 3: Therapist 1
  • Booking 4: Therapist 3

Hope this makes the question a Little bit clearer.

like image 223
ekenman Avatar asked Jul 14 '13 17:07

ekenman


1 Answers

Solve by recursion:

static IEnumerable<List<int>> GetCombinations(IEnumerable<List<int>> lists, IEnumerable<int> selected)
{
    if (lists.Any())
    {
        var remainingLists = lists.Skip(1);
        foreach (var item in lists.First().Where(x => !selected.Contains(x)))
            foreach (var combo in GetCombinations(remainingLists, selected.Concat(new int[] { item })))
                yield return combo;
    }
    else
    {
        yield return selected.ToList();
    }
}

static void Main(string[] args)
{
    List<List<int>> lists = new List<List<int>>
    {
        new List<int> { 1, 3, 6 },
        new List<int> { 1, 2, 6 },
        new List<int> { 1 },
        new List<int> { 2, 3 }
    };

    var combos = GetCombinations(lists, new List<int>()).Distinct();

    foreach (var combo in combos)
        Console.WriteLine("{ " + string.Join(", ", combo.Select(x => x.ToString())) + " }");

    return;
}

Output:

{ 3, 6, 1, 2 }
{ 6, 2, 1, 3 }
like image 115
Fung Avatar answered Nov 15 '22 15:11

Fung