问题
I am looking for a way to get all possible combinations consisting of exactly one element from each group. For my purposes, I do not care about the ordering of the elements. By that I mean {1,2} is the same as {2,1}.
Suppose I had the following 4 groups:
Group 1 = {e1, e2}
Group 2 = {e3, e4}
Group 3 = {e5, e6, e7}
Group 4 = {e8}
In this case, I think I would want (assuming that actually is all unique combinations)
{e1, e3, e5, e8}
{e1, e3, e6, e8}
{e1, e3, e7, e8}
{e1, e4, e5, e8}
{e1, e4, e6, e8}
{e1, e4, e7, e8}
{e2, e3, e5, e8}
{e2, e3, e6, e8}
{e2, e3, e7, e8}
{e2, e4, e5, e8}
{e2, e4, e6, e8}
{e2, e4, e7, e8}
How should I approach a problem such as this? My hope is that even just a hint should help me out a ton.
回答1:
Nested loops. It won't be pretty but it will work. a loop within a loop within a loop within a loop. Check each element against all other groups then check the next element. This solution will only work if you know the number of groups though. It will also be slow for large groups, O(n^4).
回答2:
for (var Item1 in Group1) {
for (var Item2 in Group2) {
for (var Item3 in Group3) {
for (var Item4 in Group4) {
echo '{'+Item1+','+Item2+','+Item3+','+Item4+')';
}
}
}
}
来源:https://stackoverflow.com/questions/23306590/all-combinations-of-elements-with-exactly-one-element-from-each-group