【发布时间】:2012-05-17 22:19:58
【问题描述】:
我想生成一个字符串列表的所有可能组合的列表(它实际上是一个对象列表,但为简单起见,我们将使用字符串)。我需要这个列表,以便我可以在单元测试中测试所有可能的组合。
例如,如果我有一个列表:
var allValues = new List<string>() { "A1", "A2", "A3", "B1", "B2", "C1" }
我需要一个 List<List<string>> 以及所有组合,例如:
A1
A2
A3
B1
B2
C1
A1 A2
A1 A2 A3
A1 A2 A3 B1
A1 A2 A3 B1 B2
A1 A2 A3 B1 B2 C1
A1 A3
A1 A3 B1
etc...
递归函数可能是获得所有组合的方法,但它似乎比我想象的要难。
任何指针?
谢谢。
编辑:两种解决方案,带或不带递归:
public class CombinationGenerator<T>
{
public IEnumerable<List<T>> ProduceWithRecursion(List<T> allValues)
{
for (var i = 0; i < (1 << allValues.Count); i++)
{
yield return ConstructSetFromBits(i).Select(n => allValues[n]).ToList();
}
}
private IEnumerable<int> ConstructSetFromBits(int i)
{
var n = 0;
for (; i != 0; i /= 2)
{
if ((i & 1) != 0) yield return n;
n++;
}
}
public List<List<T>> ProduceWithoutRecursion(List<T> allValues)
{
var collection = new List<List<T>>();
for (int counter = 0; counter < (1 << allValues.Count); ++counter)
{
List<T> combination = new List<T>();
for (int i = 0; i < allValues.Count; ++i)
{
if ((counter & (1 << i)) == 0)
combination.Add(allValues[i]);
}
// do something with combination
collection.Add(combination);
}
return collection;
}
}
【问题讨论】:
-
我知道这不是您想要的,但微软有这个系统处于测试阶段,它会自动为您生成输入组合。它被称为 Pex:research.microsoft.com/en-us/projects/pex
-
想象一个二进制计数器。这应该可以帮助您入门。
-
确实,甚至不需要递归,太好了!
标签: c# math combinations