我想生成一个字符串列表的所有可能组合的列表(它实际上是一个对象列表,但为了简单起见,我们将使用字符串)。我需要这个列表,以便我可以在单元测试中测试每种可能的组合。
例如,如果我有一个列表:
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;
}
}
您可以手动输入,利用 n 位二进制数自然对应于 n 元素集的子集这一事实。
private IEnumerable<int> constructSetFromBits(int i)
{
for (int n = 0; i != 0; i /= 2, n++)
{
if ((i & 1) != 0)
yield return n;
}
}
List<string> allValues = new List<string>()
{ "A1", "A2", "A3", "B1", "B2", "C1" };
private IEnumerable<List<string>> produceEnumeration()
{
for (int i = 0; i < (1 << allValues.Count); i++)
{
yield return
constructSetFromBits(i).Select(n => allValues[n]).ToList();
}
}
public List<List<string>> produceList()
{
return produceEnumeration().ToList();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)