Skip to content

Instantly share code, notes, and snippets.

@sudipto80
Created October 22, 2016 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudipto80/de6906a18a3f3602b2b8ffed4db61521 to your computer and use it in GitHub Desktop.
Save sudipto80/de6906a18a3f3602b2b8ffed4db61521 to your computer and use it in GitHub Desktop.
CartesianProduct
void Main()
{
Cartesian<string>(new List<List<string>>()
{
new List<string>() { "A", "B" },
new List<string>() { "C", "D", "E" }
}).Dump();
}
public static List<List<T>> Cartesian<T>(List<List<T>> sets)
{
int solutions = 1;
List<List<T>> products = new List<List<T>>();
for (int i = 0; i < sets.Count; solutions *= sets[i].Count, i++) ;
for (int i = 0; i < solutions; i++)
{
int j = 1;
List<T> current = new List<T>();
foreach (var set in sets)
{
current.Add(set[(i / j) % set.Count]);
j *= set.Count;
}
products.Add(current);
}
return products;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment