I have a minesweeper game and If there is already a mine in the location, I need to find another spot. I am using tons of if else statements. If I want to make it work 100% I would have to use an infinite amount of them. There has to be another type of loop that would to this.
I have a loop to perform the function for how ever many mines the user wants.
void assignMines(values array[row][column])
{
int i = rand()%5;
int j = rand()%5;
if (array[i][j] == MINE)
{
int k = rand()%5;
int l = rand()%5;
if (array[k][l] == MINE)
{
int m = rand()%5;
int n = rand()%5;
if(array[m][n] == MINE)
{
int o = rand()%5;
int p = rand()%5;
if(array[o][p] == MINE)
{
int q = rand()%5;
int r = rand()%5;
if(array[q][r] == MINE)
{
int s = rand()%5;
int t = rand()%5;
array[s][t] = MINE;
}else
{
array[q][r] = MINE;
}
}else
{
array[o][p] = MINE;
}
}else
{
array[m][n] = MINE;
}
}else
{
array[k][l] = MINE;
}
}else
{
array[i][j] = MINE;
}
int main()
int minecount;
cout << "Enter number of mines to place on board (5 - 10):";
cin >> minecount;
for (int i=0;i<minecount;i++)
{
assignMines(array);
}
for (int mines_placed = 0; mines_placed < total_mines;) {
int row = rand() % 5, col = rand() % 5;
if (array[row][col] == MINE) continue; // there is already a mine here
array[row][col] = MINE; // else place the mine
++mines_placed;
}
While in the limiting case the loop never halts, in practice that that isn't a problem -- your computer is fast, and the loop will iterate many millions of times before any delay is noticeable.
In limited cases it is potentially useful to create a grab bag -- to simulate "draw without replacement". A grab bag works by storing a set of candidates and shuffling them, then iterating over the shuffled candidates. That guarantees a linear bound on the amount of time spent, even as the ratio of occupied to open spaces approaches 1.
As a general note, if you need a structure which is nested very deeply (or even which should be nested to a variable depth) you can model that with functions which call themselves. The concept is called "recursion". It doesn't apply here, but your approach hints at a recursive solution.