I'm building a clone of 2048 in C with SDL2, and I'm implementing the function that adds a number randomly to an empty cell on the board. The board is representd by a 2-Dim array board[BOARD_SIZE][BOARD_SIZE], and stores the exponent for the square value(10 for 1024 and so on). There must be a 90% chance of the cell being worth 1 (i.e. 2^1) against 10% of it being 2. Here's how I implemented this
void randCell(int _board[BOARD_SIZE][BOARD_SIZE]) {
int row;
int col;
bool has_space = false;
// Check if there's any empty spaces
for (int i = 0; i < BOARD_SIZE; ++i) {
for (int j = 0; j < BOARD_SIZE; ++j) {
if (_board[i][j] == EMPTY) has_space = true;
}
}
// Randomly pick a cell until we find an empty one
// TODO: Better way to find empty cells.
if (has_space) {
do {
row = randRange(0, BOARD_SIZE - 1);
col = randRange(0, BOARD_SIZE - 1);
} while (_board[col][row]);
// Fill the cell
_board[col][row] = (randRange(1, 100) < 90) ? 1 : 2;
}
}
How can I improve this? Could I somehow decrease the number of loops my while performs by only picking a random cell from the EMPTY ones?