如何遍历此列表的所有组合 [英] how to loop through all the combinations of this list
问题描述
我有一个
List<List<int>>
,不知道每个列表中有多少个整数或者有多少个列表。
我可以使用什么类型的循环,以便我得到整数的所有可能性,这样我从每个List中得到一个整数。
例如:
这是整数列表(每行代表一个int列表,整个代表int列表列表)
1,3
2,4
3,5,6
所有组合为:(1,2,3),(1,2,5),(1,2,6),(1,4,3),(1,4,5),(1, 4,6),(3,4,3),(3,4,5),(3,4,6),
(3,2,3),(3,2, 5),(3,2,6)我想作为结果
我更喜欢将组合作为int的列表列表。
with no idea of how many integers are there in each list or how many lists are there.
what type of loop could i use so that i get all the possibilities of the integers such that I get one integer from each List.
For example:
Here is the list of integers (each line representing a List of int and the entire thing representing the List of List of int)
1,3
2,4
3,5,6
all combinations are : (1,2,3), (1,2,5), (1,2,6), (1,4,3),(1,4,5),(1,4,6),(3,4,3),(3,4,5),(3,4,6),
(3,2,3),(3,2,5),(3,2,6) which i would like as the result
I prefer to get the combinations as a List of List of int.
推荐答案
如果它只是列表中的列表,为什么不使用双循环?
If it's just a list inside a list, why not use a double for loop?
List<list><int>> mydoublelist = new List<list><int>>();
List<int> myintlist = new List<int>();
for(int i = 0; i < mydoublelist.Count; i++){
List<int> mysinglelist = mydoublelist[i];
for(int j = 0; j < mysingleist.Count; j++){
myintlist.Add(mysinglelist[j]);
}
}
</int></int></int></int></list></int></list>
注意:
- 我认为会有一个AddRange方法避免第二次循环。您可以执行类似 myintlist.AddRange(mysinglelist);
的操作。
- 如果您需要唯一的整数,则AddRange将无效并且您'我需要第二个循环。检查 mysingelist.Contains(...)
方法。
希望这会有所帮助。
Notes:
- I think there is an AddRange method wich would avoid the second loop. You could do something like myintlist.AddRange(mysinglelist);
instead.
- If you need unique integers the AddRange won't work and you'll need the second loop. Check for the mysingelist.Contains( ... )
method.
hope this helps.
这是一个解决方案。
将每个列表中的所有元素添加到一个列表中,然后置换它。
Here is a solution.
Add all elements in each list into a single list,then permute it.
//Outer is your main list which contain other lists
foreach (List<int> i in Outer)NewList.AddRange(i);
</int>
现在置换NewList集合。
这里是codeproject中的排列文章列表。使用它们中的任何一个。
Now permute NewList collection.
Here is a list of permutation articles in codeproject. use any1 of them.
这篇关于如何遍历此列表的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!