Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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