How does one fill a 2D array with 'o' at random locations when the original 30 by 30 array is full of '-'? The max size of the columns and rows is 30. The user will input the number of 'o' they would like to be randomly inputted
Here's the easy way. The problem is that it's non-deterministic in time. There are potentially better ways to do this, but again, if it's not required, don't bother.
This solution involves picking random points until we find n (in this case 25 points) that aren't already filled with 'o'.
# include <iostream>
# include <random>
staticconstexprint board_size = 30;
staticchar board[30][30] = {{0}};
int main(int, char**) {
// Get a random number generator in as few steps as possible.
// This is dubious: see
// http://www.pcg-random.org/posts/cpp-seeding-surprises.htmlauto rand = [=, r_gen{std::mt19937{std::random_device{}()}}] () mutable {
return std::uniform_int_distribution<>{0, board_size - 1}(r_gen);
};
// fill the board with '-':
for (auto&& row: board)
for (auto&& col: row) col = '-';
// number of spots to fill with 'o':
staticconstexprint num_os = 25;
// This solution has indeterminate running time. Worst case it never halts.
// You don't need to worry about this unless n is approaching (or exceeding)
// the number of elements in the board.
for (int i = 0; i < num_os;) {
auto& piece = board[rand()][rand()];
if (piece != 'o') { // place an 'o', count it.
piece = 'o'; ++i;
}
}
for (auto&& row: board) {
for (auto&& col: row) std::cout << col;
std::cout << "\n";
}
}
So kind of did something according to my friend's way http://textuploader.com/d1u10
I'm getting a logic error where it prints nothing after I call the print outside this function. "seed" is something the user inputted.
board[rand()][rand()] ... rand is up to randmax constant which is normally quite large.
youll see a lot of people using rand()%max to cap it into the desired range.
I prefer
rand()/(double)(randmax) * maxallowd. This caps it into a % and takes 0 to 100 % of the value and produces slightly more randomness. Youll want to cast it back to an integer so it can be used for array index, in this application.
Hopefully this is all working for you now, but just explaining it.