如何创建 2D 字符串数组的排列

How do I create a permutation of a 2D string array?

本文关键字:字符串 数组 排列 2D 何创建 创建      更新时间:2023-10-16

我有以下代码。我将每个框设置为等于 1。现在我想一次将 3 个框设置为 0。如何在不手动将它们中的每一个设置为 1 的情况下执行此操作?

是否有一个排列公式将当时的 3 设置为 1?

#include <iostream>
using namespace std;
int main()
{
  int array[2][2];
  for (int x = 0; x<2; x++) 
  {
        for (int y = 0; y<2; y++)
            array[x][y] = 1;
  }
 // display all cells to see that all of them are set to zero 
 cout << "diplaying" << endl;   
 for (int x = 0; x<2; x++)   
 {
    for (int y = 0; y<2; y++)
       cout << array[x][y] << " " ; 
    cout << endl;
 }

打印它看起来像这样。

1   1
1   1

现在我该如何打印

0   1          
0   0

1   0
0   0

0   0
1   0

0   0
0   1

而不必以这种方式单独设置它们?

就个人而言,我会将数组存储为大小为 n*n 的一维std::vector<int>。然后你可以非常简单地打电话给std::next_permutation()。(值得注意的是,你不必使用std::vector;只要它在内存中是连续的,你应该能够正确使用std::next_permutation()

使排列逻辑"2D"的唯一一件事就是将其打印出来。但是,您的循环按原样应该正确处理,因此也没有问题。

编辑:重新读取代码后,您无法按原样使用它。相反,您应该将 1D std::vector初始化为除位置 0 的 1 之外的所有位置。然后,它的排列将产生您想要的输出。

此外,您的打印循环将无法正确打印出数组。您可能希望:

for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 2; ++j) {
        std::cout << vector[i*2+j] << " " ;
    }
    std::cout << std::endl;
}

仔细阅读后,我是这样解释你的问题的:你想从这里开始

1   1
1   1

对此

0   1          
0   0

使用 for 子句。

如果您只想保持单元格不变..您可以保存它并在用0填充数组后恢复它。

memo = array[0][1];
for (int x = 0; x<2; x++) {
    for (int y = 0; y<2; y++) {
        array[x][y] = 0;
    }
}
array[0][1] = memo;

如果这是你想做的。

顺便说一下,"字符串数组"在哪里..?

我会写一个函数来打印所有零,除了需要打印实际值的地方,然后使用不同的索引调用这个函数以获得所需的效果。

#include <iostream>
using namespace std;
#define SZ 2
void printValue(int a [SZ][SZ], int x, int y)
{
    for(int i=0; i<SZ; ++i )
    {
        for(int j=0; j<SZ; ++j)
        {
            if(i==x && j==y) cout<<a[i][j];
            else cout<<"0";
            cout<<" ";
        }
        cout<<endl;
    }
}

现在您可以在 for 循环中使用此函数

int main()
{
  int arr[SZ][SZ];
  for (int x = 0; x<SZ; x++)
  {
        for (int y = 0; y<SZ; y++)
            arr[x][y] = 1;
  }
    // display all cells to see that all of them are set to zero
 cout << "diplaying" << endl;
 for (int x = 0; x<SZ; x++)
 {
    for (int y = 0; y<SZ; y++)
       cout << arr[x][y] << " " ;
    cout << endl;
 }
 //now display all combos:
 for(int i=0; i<SZ; ++i)
 {
     for(int j=0; j<SZ; ++j)
     {
         printValue(arr, i,j);    
     }
  cout<<"nn";
 }

}