I have a minesweeper program. What is happening is that there is a 5x5 array of * like so,
*****
*****
*****
*****
*****
And it is using the loop to assign how ever many mines the user enters to a a random spot on the array.I need the assignMines function to be a bool. I currently have it as a void. I'm not good with bool. I do know that it returns true or false. And also, sometimes it will only put 1 less amount of mines because the random spot it generates already has a mine so it just places it over it. So I also need help on where and what type of loop I should use.
1. Use std::map<size_t, std::pair<size_t,size_t>> to map natural numbers to the 2D array positions
2. std::iota a std::vector<size_t> with the #elements of the 2D array
3. std::shuffle this vector and read off it's first n elements – where n is the number of mines – this will ensure that each mine is placed at a unique spot
4. wrap this code into a function returning bool though I'm not sure what the return value is signifying – if the function is written properly it should always return true
I think the assignMines function is OK as void. It is the minefield array that needs to be of bool type - each point is either mined (true) or not (false).
The function is supposed to be a bool. Here is the part that says so.
In the code I attached,
values array[row][column]; is correct
You will then assign the number of mines between 5 and 10, inclusively, specified by the user to randomly generated locations on the board using a bool function, passing in the two-dimensional array and the size. This function will generate a random row- column position and then attempt to place a mine at that row-column position on the board. Since the row-column position is randomly generated, if the function attempts to place a mine on a square that already contains a mine, the method will return false, indicating that the assignment was not successful. If the square, however, does not already contain a mine, then the function will assign a mine to that location by assigning that row-column position with the enumerated type representing the mine and return true, indicative that the assignment was successful. Note that this function attempts to place only one (1) mine at a randomly generated location on the board, so a loop should be implemented in the calling function to achieve this functionality.
Your instructions are alluding to a function that attempts successfully, or unsuccessfully place one mine at a time.
Taking lastchance's suggested code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// New function to attempt to place one mine
bool place_one_mine ()
{ int i = rand()%ROW;
int j = rand()%COL;
if (mineArray[i][j]) // already mined ...
returnfalse; // Can't place a mine there
mineArray[i][j] = true; // ... then add a mine
returntrue; // Successful
}
void assignMines( int num )
{ int count = 0;
while (count < num)
{ if (place_one_mine ())
count++;
}
}