Created
October 22, 2016 10:00
-
-
Save sudipto80/de6906a18a3f3602b2b8ffed4db61521 to your computer and use it in GitHub Desktop.
CartesianProduct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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