Skip to content

Instantly share code, notes, and snippets.

@stdray
Created May 22, 2014 15:30
Show Gist options
  • Save stdray/90f5fec2f0230f7a6d4c to your computer and use it in GitHub Desktop.
Save stdray/90f5fec2f0230f7a6d4c to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
namespace PermutationsMany
{
public class Program
{
public static void Main()
{
var collections = new[] { new[] { 1, 2, }, new[] { 4, 5, 100, 234 }, new[] { 6, 7 } };
foreach (var permutation in PermutationsMany(collections))
Console.WriteLine(string.Join(", ", permutation));
Console.ReadKey();
}
public static IEnumerable<T[]> PermutationsMany<T>(IList<T[]> collections)
{
var indexes = new int[collections.Count];
while (indexes[0] < collections[0].Length)
{
var current = collections.Count - 1;
var item = new T[collections.Count];
for (var i = 0; i < collections.Count; i++)
item[i] = collections[i][indexes[i]];
yield return item;
indexes[current]++;
for (; current > 0 && indexes[current] >= collections[current].Length; current--)
indexes[current - 1]++;
for (var i = current + 1; i < indexes.Length; i++)
indexes[i] = 0;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment