如何使用Every Possible Combination填充2D数组? C ++逻辑

时间:2014-12-10 10:24:50

标签: c++ arrays logic 2d combinations

我无法弄清楚这一背后的逻辑......这是我到目前为止所拥有的:

#include <iostream>
using namespace std;

int thearray[4][4];
int NbPos = 4;

int main() {
    int i2;
    int q2;

    for(int i = 1; i < 4; i++) { 
        for(int q = 1; q < 4; q++) { 
            for(int c = 0; c < NbPos; c++) {
                thearray[i][q] = c;
            }
        }
    }
}

这是填充阵列到最后仍然是:

3 3 3
3 3 3
3 3 3

但它没有在任何可能的组合附近碰到任何东西 理想情况下,一旦达到:

0 0 0
0 0 0
0 0 3

下一步应该是:

0 0 0
0 0 0
0 1 0

所以它达到了TON的组合。关于如何让它成功的任何想法?我对这个逻辑感到难过!

2 个答案:

答案 0 :(得分:1)

通过迭代这种方式,一维数组将使循环更简单。你仍然可以在精神上对待它有行和列,但它们只是在代码中端到端地布局。

你可以尝试这样的事情;但是如果你想要它以2D格式特别挑战留给你;)

#include <iostream>

using namespace std;

#define rows 4
#define columns 4

int main() {

    int thearray[rows * columns] = {0};
    int NbPos = 4;
    int lastPos = rows * columns - 1;

    while (true) {
        thearray[lastPos]++;

        int pos = lastPos;
        while (thearray[pos] == NbPos and pos >= 1) {
            thearray[pos - 1]++;
            thearray[pos] = 0;
            pos--;
        }

        bool finished = true;
        for (int i = 0; i < rows * columns; i++) {
            if (thearray[i] != NbPos - 1) {
                finished = false;
            }
        }

        if (finished) {
            break;
        }
    }

    for (int i = 0; i < rows * columns; i++) {
        std::cout << thearray[i] << " ";
        if (i % rows == rows - 1) {
            cout << endl; // makes it look like a 2D array
        }
    }
}

答案 1 :(得分:0)

将最终形式设为全3是有意义的,因为你循环数组的每个元素,并在最后用3分配它。

因此,下一个元素只考虑与前一个元素的最终值(将为3)的组合。

用数学术语思考,你的复杂性是N ^ 3可以这么说(实际上是N ^ 2 * 4,但因为你的N是3 ......)。 你的方法是错误的,因为你想找到由因子函数定义的排列,而不是政治函数。

输出的必要复杂性与算法的复杂性不相匹配(对于所需的输出量,您的算法速度非常快)。

您正在寻找的是回溯(反向收集将与您的输出所需的复杂性相匹配)。

递归函数应该是这样的(考虑一维数组,有9个元素):

 RecursiveGeneratePermutations(int* curArray, int curIdx)
 {
    if (curIDX==9)
    {
       for (int i=0; i<9;i++)
       {
           // write the array
       }
    } else {
       curArray[curIdx]=0;
       RecursiveGeneratePermutations(curIdx+1);
       curArray[curIdx]=1;
       RecursiveGeneratePermutations(curIdx+1);
       curArray[curIdx]=2;
       RecursiveGeneratePermutations(curIdx+1);
       curArray[curIdx]=3;
       RecursiveGeneratePermutations(curIdx+1);
    }
 }

现在你只需要调用索引0的函数:

RecursiveGeneratePermutations(arrayPtr,0);

然后等待......分配:)。