Skip to content

Instantly share code, notes, and snippets.

@sudipto80
Last active January 4, 2016 09:06
Show Gist options
  • Save sudipto80/13edf7feae26d4215e09 to your computer and use it in GitHub Desktop.
Save sudipto80/13edf7feae26d4215e09 to your computer and use it in GitHub Desktop.
CartesianProduct
void Main()
{
Cartesian<int>(new List<List<int>>()
{new List<int>(){1,2,3},
new List<int>(){3,2},
new List<int>(){5,6,7}}).Dump();
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;
}
// Define other methods and classes here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment