生成字符串列表的所有组合

L-F*_*our 16 c# math combinations

我想生成一个字符串列表的所有可能组合的列表(它实际上是一个对象列表,但为了简单起见,我们将使用字符串).我需要这个列表,以便我可以在单元测试中测试每个可能的组合.

例如,如果我有一个列表:

  var allValues = new List<string>() { "A1", "A2", "A3", "B1", "B2", "C1" }
Run Code Online (Sandbox Code Playgroud)

我需要一个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...
Run Code Online (Sandbox Code Playgroud)

递归函数可能是获得所有组合的方法,但它似乎比我想象的更难.

有什么指针吗?

谢谢.

编辑:两个解决方案,有或没有递归:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*lad 13

您可以手动制作,使用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();
}
Run Code Online (Sandbox Code Playgroud)