1

I am trying to randomly fill a 10x10 grid with 10 characters of H, 5 char of ~ and 5 char of * and the rest with (blank space). I can't think of a way to limit the outcomes to my desired limit.

This is what I have so far.

cout <<"GRID: \n"<<"______________________________\n";
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < 10; j++){
            char contents[4] = {'~','H',' ','*'};
                char arrBoard[i][j];

            arrBoard[i][j] = contents[rand() % 4] ;
                    cout <<"| "<< arrBoard[i][j];
        }
        cout<<" "<<endl;
    }
Max Langhof
  • 23,383
  • 5
  • 39
  • 72
  • as i mentioned, I want 10 h's, 5 ~'s, 5 *'s and the rest 80 blank spaces. Thank you! – veronica200011 Dec 13 '19 at 09:21
  • 3
    You can simply generate a vector with 10 `H`, 5 `~`, 5 `*` and 80 ' ', and then apply a random permutation on this vector. Look at `std::shuffle` – Damien Dec 13 '19 at 09:22
  • 1
    Create an array containing ten `'H'`, five `~`, five `*`, and eighty `' '` - so it has exactly 100 characters. Shuffle it (e.g. using the standard algorithm `std::shuffle()` in C++11 and later). Now you have a hundred shuffled characters, with the number of each character as specified. Use a loop (or a pair of nested loop) to copy that shuffled array of 100 characters into your 10x10 array. As long as you ensure every character is copied exactly once without overwriting then (I'll leave that as an exercise) you'll get the result you seek. – Peter Dec 13 '19 at 09:26

1 Answers1

4

Put these characters into a string:

std::string chars = std::string(10, 'H') + std::string(5, '~') + std::string(5, '*');
chars.resize(100, ' ');

shuffle it:

std::shuffle(chars.begin(), chars.end(), std::mt19937(std::random_device{}()));

and then use it to populate the grid:

constexpr std::size_t n = 10;
char arrBoard[n][n];

assert(chars.size() == n * n);
auto it = chars.begin();
for (std::size_t i = 0; i < n; ++i)
    for (std::size_t j = 0; j < n; ++j)
        arrBoard[i][j] = *it++;
Evg
  • 25,259
  • 5
  • 41
  • 83