我想生成一个字符串列表的所有可能组合的列表(它实际上是一个对象列表,但为简单起见,我们将使用字符串)。我需要这个列表,以便我可以在单元测试中测试每个可能的组合。
例如,如果我有一个列表:
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;
}
}