0

If I have list lets say for ex. four different list of numbers and i want to get all the different combinations between those, how can I achive it.

This could be what I want to bring as an input.

{1, 2, 3}
{2, 4}
{3, 4}
{5, 6}

And result should be something like this:

[[1, 2, 3, 5], [1, 2, 3, 6], [1, 2, 4, 5], [1, 2, 4, 6], [1, 4, 3, 5], [1, 4, 3, 6], [1, 4, 4, 5], [1, 4, 4, 6], [2, 2, 3, 5], [2, 2, 3, 6], [2, 2, 4, 5], [2, 2, 4, 6], [2, 4, 3, 5], [2, 4, 3, 6], [2, 4, 4, 5], [2, 4, 4, 6], [3, 2, 3, 5], [3, 2, 3, 6], [3, 2, 4, 5], [3, 2, 4, 6], [3, 4, 3, 5], [3, 4, 3, 6], [3, 4, 4, 5], [3, 4, 4, 6]]

I found this what is quite close what I try to do, but couldn't solve it. What is the best way to find all combinations of items in an array?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    If the length of the list is always 4 you could do four nested loops. If it varies I'd use recursion with an iteration of the current list at its core. – 500 - Internal Server Error Feb 21 '23 at 16:07
  • You could merge the input arrays into one and then use the solution in the link you provided (or maybe I misunderstood the question)? – Johan Donne Feb 21 '23 at 16:09
  • @JohanDonne it looks like OP is looking for Cartesian Product (pick one from each array for every output) and not "combinations". user - please [edit] question if duplicate I selected is *not* what you are looking for so question can be re-opened. – Alexei Levenkov Feb 21 '23 at 16:45

1 Answers1

1

If items within each array are unique, you can put something like this (let's generalize the routine):

using System.Linq;

...

private static IEnumerable<T[]> Combinations<T>(params T[][] table) {
  int[] indexes = new int[table.Length];

  do {
    yield return indexes.Zip(table, (index, line) => line[index]).ToArray();

    for (int i = indexes.Length - 1; i >= 0; --i)
      if (indexes[i] == table[i].Length - 1)
        indexes[i] = 0;
      else {
        indexes[i] += 1;

        break;
      }
  } 
  while (indexes.Any(item => item != 0));
}

Demo:

int[] a = { 1, 2, 3 };
int[] b = { 2, 4 };
int[] c = { 3, 4 };
int[] d = { 5, 6 };

int[][] result = Combinations(a, b, c, d).ToArray();

// Let's have a look
var report = string.Join(Environment.NewLine, result
  .Select(array => string.Join(", ", array)));

Console.WriteLine(report);

Output:

1, 2, 3, 5
1, 2, 3, 6
1, 2, 4, 5
1, 2, 4, 6
1, 4, 3, 5
1, 4, 3, 6
1, 4, 4, 5
1, 4, 4, 6
2, 2, 3, 5
2, 2, 3, 6
2, 2, 4, 5
2, 2, 4, 6
2, 4, 3, 5
2, 4, 3, 6
2, 4, 4, 5
2, 4, 4, 6
3, 2, 3, 5
3, 2, 3, 6
3, 2, 4, 5
3, 2, 4, 6
3, 4, 3, 5
3, 4, 3, 6
3, 4, 4, 5
3, 4, 4, 6
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215