【问题标题】:generate all combination of elements in 2d vector [duplicate]生成二维向量中元素的所有组合[重复]
【发布时间】:2011-12-23 19:48:38
【问题描述】:

可能重复:
How can I create cartesian product of vector of vectors?

我在弄清楚如何在二维向量中生成所有元素组合时遇到了一些逻辑问题。在这里,我创建了一个 2D 矢量。两个维度的大小都不能假设。

#include <iostream>
#include <vector>

using namespace std;

int main() {
  srand(time(NULL));
  vector< vector<int> > array;

  // This creates the following:
  // array[0]: {0, 1, 2} 
  // array[1]: {3, 4, 5, 9} 
  // array[2]: {6, 7, 8} 
  for(int i=0; i<3; i++) { 
    vector<int> tmp;
    tmp.push_back((i*3)+0); tmp.push_back((i*3)+1); tmp.push_back((i*3)+2);
    if(i==1)
      tmp.push_back((i*3)+6);
    array.push_back(tmp);
  }
}

创建向量后,我想输出所有可能的组合如下:

  comb[0] = {0, 3, 6}
  comb[1] = {0, 3, 7}
  comb[2] = {0, 3, 8}
  comb[3] = {0, 4, 6}
  comb[4] = {0, 4, 7}
  comb[x] = {...}

但是,我在如何概念化循环结构以正确执行此操作时遇到了麻烦,其中大小“数组”和每个子数组中的元素是未知/动态的。

编辑 1:不能假设有 3 个数组。其中有 array.size() ;)

【问题讨论】:

  • 我可能可以帮助你,但请解释更多mathematically你的实际意思。
  • 它可能是一个carthesian产品吗?对于 5 个数组 ABCDE 作为输入,您是否期望 a 来自 A、b 来自 B 等所有可能的 5 元组 (abcde)?

标签: c++ algorithm combinations


【解决方案1】:

未知大小的最简单方法是递归。

void combinations(vector<vector<int> > array, int i, vector<int> accum)
{
    if (i == array.size()) // done, no more rows
    {
        comb.push_back(accum); // assuming comb is global
    }
    else
    {
        vector<int> row = array[i];
        for(int j = 0; j < row.size(); ++j)
        {
            vector<int> tmp(accum);
            tmp.push_back(row[j]);
            combinations(array,i+1,tmp);
        }
    }
}

最初使用i = 0 和一个空的accum 调用。

【讨论】:

  • 完美运行,非常感谢!
【解决方案2】:

你有三个数组,对吧?他们每个人的大小都是不同的,你想要所有的组合。如果是这样,这应该对您有所帮助:

伪代码:

for(i=0; i<size(array0), i++) {
   for(j=0; j<size(array1), j++) {
       for(k=0; k<size(array2), k++) {
          print("{array0[i], array1[j], array2[k]} \n");

       }
   }
}

希望你能重写成C++代码

编辑:这应该适用于任意数量的数组

第一个for 只是打印,第二个for 移动数组的索引(关心溢出)

又是伪代码:

comb = 0;
stop = false; 
while(!stop) {
   output("Combination["+comb+"] = {");
   for(i = 0; i < num_of_arrays; i++) {
     index = index_array[i];
     output(array[i][index]); // assume this function takes care about right formatting

   }
   output("}\n");

   index_array[num_of_arrays-1]++;

   for(i = num_of_arrays-1; i >= 0; i--) {
     index = index_array[i]
     if(index == size(array[i]) {
        if(i == 0)
           stop = true;
        else {
           index_array[i] = 0;
           index_array[i-1]++;
        }
     }
   }
   comb++;
}

希望这会有所帮助!

【讨论】:

  • 所以诀窍/挑战是我不能假设只有 3 个数组,否则我完全同意你的解决方案。
  • 编辑后查看代码
  • 什么是index_array[],它是如何初始化的?
  • index_array - 计数器数组(直到你正在运行的数组索引) - 用 0 初始化
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 2022-01-25
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多