I have 2D array as a grid that can be thought a game board. When the board is initialized so the game is started there are four men. It works for nxn
grid. As an example
我有2D数组作为网格,可以被认为是一个游戏板。当棋盘初始化以便比赛开始时,有四个人。它适用于nxn网格。举个例子
x o
o x
I do it using a 2D array. Now, I try to convert the array to 1D. I'm stuck on how I can put the symbols on the grid for 1D array.
我是用2D数组做的。现在,我尝试将数组转换为1D。我坚持如何将符号放在网格上的1D数组。
for(int i = 0; i < row; ++i)
for(int j = 0; j < col; ++j)
{
//grid[i][j] = '.';
grid[i * col + j] = '.'; // I've converted the part
}
int centerh = row / 2;
int centerw = col / 2;
// I'm stuck that part.
grid[centerh][centerw] = 'o';
grid[centerh - 1][centerw - 1] = 'o';
grid[centerh][centerw - 1] = 'x';
grid[centerh - 1][centerw] = 'x';
2 个解决方案
#1
1
This converts your 2D grid into 1D :
这会将您的2D网格转换为1D:
grid1D[row*col];
grid2D[row][col];
for(int i = 0; i < row; ++i)
for(int j = 0; j < col; ++j)
grid1D[i * col + j] = grid2D[i][j];
#2
1
In C I would use macros and a 1D array s a basis for this sort of thing.
在C中我会使用宏和一维数组作为这种事情的基础。
Something like :
就像是 :
#define WIDTH 10
#define HEIGHT 10
char grid[ WIDTH * HEIGHT ] ;
#define ELEMENT(row,column) grid[ ( (row)*WIDTH ) + (column) ]
/* Read an element */
char c ;
c = ELEMENT( 5, 7 ) ;
/* write to an element */
ELEMENT( 5, 7 ) = 'x' ;
/* access the array in 1D is trivial as you simply use grid[] directly */
So you can use the same 1D array as a 2D item without duplication.
因此,您可以使用相同的1D数组作为2D项目而无需重复。
One important point : avoid post- and pre- decrement operations when using macros. The reason for this is that they can lead to confusing errors, as macros are not functions and each "parameter" of the macro is simply text that replaces the corresponding macro "parameter".
重要的一点是:在使用宏时避免后期和预先减量操作。这样做的原因是它们可能导致混淆错误,因为宏不是函数,宏的每个“参数”只是替换相应宏“参数”的文本。
#1
1
This converts your 2D grid into 1D :
这会将您的2D网格转换为1D:
grid1D[row*col];
grid2D[row][col];
for(int i = 0; i < row; ++i)
for(int j = 0; j < col; ++j)
grid1D[i * col + j] = grid2D[i][j];
#2
1
In C I would use macros and a 1D array s a basis for this sort of thing.
在C中我会使用宏和一维数组作为这种事情的基础。
Something like :
就像是 :
#define WIDTH 10
#define HEIGHT 10
char grid[ WIDTH * HEIGHT ] ;
#define ELEMENT(row,column) grid[ ( (row)*WIDTH ) + (column) ]
/* Read an element */
char c ;
c = ELEMENT( 5, 7 ) ;
/* write to an element */
ELEMENT( 5, 7 ) = 'x' ;
/* access the array in 1D is trivial as you simply use grid[] directly */
So you can use the same 1D array as a 2D item without duplication.
因此,您可以使用相同的1D数组作为2D项目而无需重复。
One important point : avoid post- and pre- decrement operations when using macros. The reason for this is that they can lead to confusing errors, as macros are not functions and each "parameter" of the macro is simply text that replaces the corresponding macro "parameter".
重要的一点是:在使用宏时避免后期和预先减量操作。这样做的原因是它们可能导致混淆错误,因为宏不是函数,宏的每个“参数”只是替换相应宏“参数”的文本。