【问题标题】:Find all the combinations for n sets of k elements找出 n 组 k 个元素的所有组合
【发布时间】:2013-05-05 16:36:46
【问题描述】:

我有一个结构数组

typedef struct st1
{
  double start;
  double step;
  double stop;
} ST;

我需要找到这些优化参数的所有可能组合,从开始到逐步停止。

例如:

array[0].start = 0
array[0].step = 1
array[0].stop = 2

array[1].start = 5
array[1].step = 1
array[1].stop = 6

组合将是:

0,5 0,6 1,5 1,6 2,5 2,6

¿如何在 C 语言中为 N 大小的选项数组实现此功能?

for(i=0; i<n; i++){
  ....
}

【问题讨论】:

  • 嗯...当具有固定数组大小时,我已经解决了嵌套循环的类似问题。问题是数组大小是可变的。我不是在寻找实现,而是在寻找如何实现它的线索。无论如何,感谢您的评论。我希望我还在做作业,但那是很久以前的事了;)
  • @JimMischel:可能是重复的,但不是那个帖子。这似乎是关于排列而不是组合、OP 的标题和术语的混淆使用。

标签: c algorithm loops combinations


【解决方案1】:

一些伪代码(实际上是Kalkulon代码)可以简单地翻译成C代码:

::array={{0,1,2},{5,1,6}},
::N=Size(array),
::combination={0,0},

comb()=
(
 n=0,
 do(
  finishCtr = 0,
  i = n,
  for(j = 0; j < N; j++; // do
   maxsteps=(array[j,2] - array[j,0]) / array[j,1] + 1,
   steps = i % maxsteps, // modulo
   i = ip(i / maxsteps), // integer division
   elem = array[j,0] + steps * array[j,1],
   if(i > 0 && steps == 0; finishCtr++),  
   combination[j] = elem
  ),
  // print result if not already all combinations are done 
  if(finishCtr < N; PrintLn((string)combination)),
  n++
 ; // do-while 
 finishCtr < N
 )
);

输出:

{0, 5}
{1, 5}
{2, 5}
{0, 6}
{1, 6}
{2, 6}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2021-11-14
    相关资源
    最近更新 更多