Reputation: 1165
This it my code for generating random mines in a 10x10 minesweeper game board.
for (int j = 0; j < 10; j++) {
mine[j] = (int) (Math.random() * 100);
while (board[mine[j]] != 99)
board[mine[j]] = 99;
}
I want to modify it to work in a 2D int array:
for (int j = 0; j < 10; j++) {
do {
temp = (int) (Math.random() * 100);
row = temp / 10;
column = temp % 10;
} while (board[row][column] != 99);
board[row][column] = 99;
}
However this code, creates an infinite loop. I'm stuck and i can't think of why its not working
Upvotes: 0
Views: 146
Reputation: 831
Why does your code create an infinite loop? Initially none of the cells have 99 as a value and your do_while
condition is while (board[row][column] != 99);
. So the loop will keep on iterating since it can never encounter a cell with value 99.
Your do_while
condition is wrong. It should be while (board[row][column] == 99);
Explanation: The row and column number will be regenerated if the currently generated random cell has a mine i.e. if the cell value is equal to 99. The do_while
loop will keep on running until the generated cell location doesn't already have a mine.
I believe this is what you wanted to do.
Note that your algorithm for generating mines is not optimal. There are better ways to do this.
Upvotes: 0
Reputation: 11280
Syntactically your problem is in the while condition, but your algorithm is also not optimal since collisions with already placed bombs will get more and more frequent. In the extreme case, having to fill all but one position on the board, you may have to reroll lots of times before hitting a free spot.
It is better to draw slots from a set that only contains free positions.
// create an array of slots to draw ten slots from
int[] slots = new int[100];
for (int i = 0; i < slots.length; i++) {
slots[i] = i;
}
/*
* draw ten slots by placing them at the start of the array
* subsequent draws will draw from the tail of the array
*/
Random random = new Random();
for (int i = 0; i < 10; i++) {
// draw from one of the slots from the tail
int draw = random.nextInt(100 - i) + i;
// switch values at draw and i index
int temp = slots[draw];
slots[draw] = slots[i];
slots[i] = temp;
// use the draw to place a bomb on the board
board[(draw / 10)][(draw % 10)] = 99;
}
Upvotes: 0
Reputation: 10151
I think you meant: [while
condition was wrong, why would you want to set a field that is already 99 to 99]
for (int j = 0; j < 1; j++) {
do {
temp = (int) (Math.random() * 100);
row = temp / 10;
column = temp % 10;
} while (board[row][column] == 99);
board[row][column] = 99;
}
Upvotes: 3