【问题标题】:Combination C code for a random set of integers一组随机整数的组合 C 代码
【发布时间】:2011-09-19 01:40:22
【问题描述】:

我有一个随机集合 S={3,12,15,24,33,40},我需要从这个集合中生成大小为 3 的子集。关于组合的大多数示例和解释都涉及一组递增和S1={1,2,3,4,...n} 等有序值。使用组合公式,我发现可能的组合数量为 20,但无法弄清楚如何在 C 中生成该列表。

如果集合像上面的 S 一样是随机的,我如何在 C 中获得没有重复的可能列表?

谢谢。

【问题讨论】:

  • 需要生成所有组合还是随机生成单个组合?
  • 组合列表 - 为此我猜测有 20 种组合,稍后我将对其进行排序。

标签: c algorithm combinations


【解决方案1】:

使用您看到的具有递增、有序值的算法,并简单地将这些算法替换为您列表中的值。

例如,组合(0-indexed)将是:

0, 1, 2
0, 1, 3
0, 1, 4
...
...

然后有一个包含你的数字的数组

int array[] = { ...values... };

并将组合更改为:

array[0], array[1], array[2]
array[0], array[1], array[3]
...
...

【讨论】:

    【解决方案2】:

    您可以递归地生成 n 个项目的所有组合。这样的事情应该可以工作:

    void combos(int[] values, int[] used, int[] selected, int len, int needed, int next) {
        int i;
        if (needed > 0) {
            /* select each available item as the next item and recurse */
            for (i = 0; i < len; i++) {
                if (!used[i]) {
                    used[i] = 1;
                    selected[next] = values[i];
                    combos(values, used, selected, len, needed-1, next+1);
                    used[i] = 0;
                }
            }
        } else {
            /* selected[0] .. selected[next-1] contains a combination */
            reportCombination(selected, next);
        }
    }
    

    使用next=0needed=3 调用它以使球滚动,它应该生成20 次对reportCombination 的调用,每个调用都有3 个值的唯一组合。 (如果需要收集所有组合的数组,则不需要reportCombination,但需要额外的簿记参数或一些全局变量。)

    【讨论】:

      【解决方案3】:

      您要的是 SPower set 的一个子集,按约定称为 P(S) — 即 Power 集中的所有三元素集 P(S)。

      您可以修改this C code example 中的幂集函数以输出特定基数(计数)的集。

      【讨论】:

        【解决方案4】:

        通过删除重复,再次使用同一集合的笛卡尔积,, 试试这个代码,

        int array[6]={3,12,15,24,33,40};
        int combinations[20][3];
        int n=0;
        for(i=0;i<4;i++)
        {                      //loops for 1st num in combination
           for(j=i+1;j<5;j++)
           {                       //loops for 2nd num in combination
             for(k=j+1;k<6;k++)
             {                         //loops for 3rd num in combination
                combinations[n++]={array[i],array[j],array[k]};
             }
           }
        }
        

        最后的组合二维数组将包含所有可能的数字组合而不重复

        【讨论】:

          猜你喜欢
          • 2015-09-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-12
          • 2012-02-10
          • 2018-02-10
          • 1970-01-01
          相关资源
          最近更新 更多