2d array and random numbers

so im doing this project for my cs class and we have create a simple minesweeper game. in one particular part at the beginning of the program i have to write a function to start a new game. i have to generate 10 bombs (represented by -1) randomly into my 2d array, how do i check for duplicates, because they generate on the board...but sometimes only 8 or 9 show up due to the rand generating one in the same spot twice.

here is my for loop for generating the 10 bombs:

for(int i=0; i<10; i++){
a[rand() % 10][rand() % 10] = -1; //the array (a) is [10][10]
}
You could count the number of bombs already placed, and use a while-loop until there are 10 bombs
Why don't you check to see if a[ x ][ y ] already contains -1 before putting one there?
is this "legal"? will i foresee any problems with this code? the thing is, my teacher made it to where they can seed the random themselves,making it srand(seed) and they input a number for seed, and lower numbers, such as 1-90 work fine and makes 10 bombs...but then i tried something like 10000 and it only made 9 bombs.

for(int i=0; i<10; i++){
a[rand() % 10][rand() % 10];

if (a[rand() % 10][rand() % 10] == -1)
i--;
else
a[rand() % 10][rand() % 10] = -1;
}
Last edited on
NEVERMIND I GOT IT!! =) lol

1
2
3
4
5
6
7
8
9
for(int i=0; i<10; i++){
		int temp1 = rand() % 10;
		int temp2 = rand() % 10;
	
		if (a[temp1][temp2] == -1)
			i--;
		else 
		       a[temp1][temp2] = -1;
}

Yup. Now it's kinda nasty to dorking with the for() loop index like you are doing. I think a simpler solution is something like this:

1
2
3
4
int numBombsPlaced = 0;
while( numBombsPlaced < 10 ) {
  // ...
}

Topic archived. No new replies allowed.