Reputation: 319
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
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.
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';
Upvotes: 0
Views: 2090
Reputation: 965
In C I would use macros and a 1D array s a basis for this sort of thing.
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.
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".
Upvotes: 1
Reputation: 32046
This converts your 2D grid into 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];
Upvotes: 1