randomized 2d array

closed account (9Nh5Djzh)
Hi everyone!
I need help with a 2d array that's 80x20 and has 100 elements placed randomly in it, the other elements are blank spaces so it'll look like a starry sky.
I have a preliminary code figured out, but I need a mechanism that'll set 100 "*" elements randomly in the array. I was thinking maybe an if else statement would work, but am at a loss as to how that should be done.
If someone could point me in the right direction that would be magnificent!


#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
const int rows = 80; // declares the amount of rows in the 2d array
const int cols = 20; // declares the amount of columns in the 2d array
int sky [rows][cols]; // declares the integers in the 2d array
unsigned seed = time(0);
srand(seed);
int i [100];

for(int r = 0; r < rows; r++)
{
for(int j = 0; j < cols; j++)
{

if(something that puts the 100 elements randomly in the array)
{
cout << " * ";
}
else // puts a blank space between the stars
{
cout << " ";
}
}

}
return 0;
}

Thanks!!!!
Last edited on
random_shuffle() can do this easily:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    const int rows = 80;
    const int cols = 20;
    char sky[rows][cols];

    // fill the first 100  with stars
    fill_n(&sky[0][0], 100, '*');
    // fill the rest with spaces
    fill_n(&sky[0][0] + 100, rows*cols - 100, ' ');
    // shuffle
    random_shuffle(&sky[0][0], &sky[0][0] + rows*cols);

    for(int r = 0; r < rows; ++r) {
       for(int c = 0; c < cols; ++c)
           cout << sky[r][c];
       cout << '\n';
    }
}
closed account (9Nh5Djzh)
Awesome! Thanks Cubbi!!
Topic archived. No new replies allowed.