Create a program that prints a 20 by 20 block. Print "[ ]" for an open space. Print [X] for closed space

Hi, I am very new to C++ and for our homework we have gotten this as a problem. I would usually assume that we would use an array for this, but he wants us to use loops that randomly are open ([]) or closed ([X]) spaces. My biggest question is how do I choose to have the 20x20 be random [] or [X] (we have only learned how to make them random numbers). I am not very far in my code but here is what I have so far if it helps at all. Also, the user of the program should have the option of modifying the ratio of empty spaces to solid spaces. Options should include 1 solid space per open space, 2 solid spaces per open space, and 3 solid spaces per open space.


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

using namespace std;

int main() {


for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
cout << rand() << rand();
}
cout << "\n";
}
Last edited on
if(rand()%2)
cout << "[X]";
else
cout << "[ ]";

Flatten your array to 20x20=400 positions.
Choose, by random selection, the ones you want to be OPEN: say n distinct ones of them.

If it is 1 solid space per open space then n=200 (half of the whole).
If it is 2 solid spaces per open space then n=133 (one third of the while).
If it is 3 solid spaces per open space then n=100 (one quarter of the whole)

You can choose numbers between 0 and 399 inclusive by rand()%400 (or by some of the more advanced functions in <random>).

You can avoid duplicates by either putting them in a set until the size is 400, or putting the appropriate number in an array and using shuffle().

You can unflatten your array of 400 simply by taking 20 at a time.

20 is also a "magic number" and you may easily replace it by N, where N need be set only once.





Last edited on
Topic archived. No new replies allowed.