c# - 生成所有可能的组合

标签 c# combinatorics cartesian-product

给定2个数组Array1 = {a,b,c...n}Array2 = {10,20,15....x}我如何生成所有可能的组合作为字符串a(i)b(j)c(k)n(p)
哪里

1 <= i <= 10,  1 <= j <= 20 , 1 <= k <= 15,  .... 1 <= p <= x


如:

a1 b1 c1 .... n1  
a1 b1 c1..... n2  
......  
......  
a10 b20 c15 nx (last combination)


因此,在所有的组合总数中,= array2 = (10 X 20 X 15 X ..X x)个元素的乘积

类似于笛卡尔乘积,其中第二个数组定义第一个数组中每个元素的上限。

固定数字示例

    Array x =  [a,b,c]
    Array y =  [3,2,4] 


因此,我们将有3 * 2 * 4 = 24个组合。结果应为:

    a1 b1 c1  
    a1 b1 c2  
    a1 b1 c3  
    a1 b1 c4  

    a1 b2 c1  
    a1 b2 c2  
    a1 b2 c3  
    a1 b2 c4


    a2 b1 c1  
    a2 b1 c2  
    a2 b1 c3  
    a2 b1 c4  

    a2 b2 c1  
    a2 b2 c2  
    a2 b2 c3  
    a2 b2 c4


    a3 b1 c1  
    a3 b1 c2  
    a3 b1 c3  
    a3 b1 c4  

    a3 b2 c1  
    a3 b2 c2  
    a3 b2 c3  
    a3 b2 c4 (last)

最佳答案

using System;
using System.Text;

public static string[] GenerateCombinations(string[] Array1, int[] Array2)
{
    if(Array1 == null) throw new ArgumentNullException("Array1");
    if(Array2 == null) throw new ArgumentNullException("Array2");
    if(Array1.Length != Array2.Length)
        throw new ArgumentException("Must be the same size as Array1.", "Array2");

    if(Array1.Length == 0)
        return new string[0];

    int outputSize = 1;
    var current = new int[Array1.Length];
    for(int i = 0; i < current.Length; ++i)
    {
        if(Array2[i] < 1)
            throw new ArgumentException("Contains invalid values.", "Array2");
        if(Array1[i] == null)
            throw new ArgumentException("Contains null values.", "Array1");
        outputSize *= Array2[i];
        current[i] = 1;
    }

    var result = new string[outputSize];
    for(int i = 0; i < outputSize; ++i)
    {
        var sb = new StringBuilder();
        for(int j = 0; j < current.Length; ++j)
        {
            sb.Append(Array1[j]);
            sb.Append(current[j].ToString());
            if(j != current.Length - 1)
                sb.Append(' ');
        }
        result[i] = sb.ToString();
        int incrementIndex = current.Length - 1;
        while(incrementIndex >= 0 && current[incrementIndex] == Array2[incrementIndex])
        {
                current[incrementIndex] = 1;
                --incrementIndex;
        }
        if(incrementIndex >= 0)
            ++current[incrementIndex];
    }
    return result;
}

关于c# - 生成所有可能的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13616545/

相关文章:

java - 如何从多个列表中获取笛卡尔积?

java - 任意数量集合的笛卡尔积

c# - 尝试改进多页 TIFF 文件分割

c# - 覆盖属性的 XML 注释

javascript - 在 IIS 上使用 HTML5/Javascript 项目和单独的 ASP.NET Web API 项目部署解决方案

algorithm - 计算给定数字在有序集合中的索引

ruby - 在 Ruby 中生成所有可能的字符串排列

c# - 如何获取嵌入式资源的路径?

python - 从列表中获取所有成对组合

java - 如何有效地对抽象列表进行嵌套迭代?