2D Bool Array

I have a two dimensional bool array that I have initialized to false through a constructor, and a print function that displays the results as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
   01234567890123456789
 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19


The print function displays the row and column labels and a space " " for each element initialized to false. If an element were to have a value of zero, then an asterisk '*' is to be displayed.

How do I get the 2D array to have a random assortment of " " and '*' so I can test the array with other functions that will determine things like row count and column count and more. An example will be like below, but does not have to be that complex.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
01234567890123456789
 0                    
 1         *        * 
 2       *   * ***  * 
 3       *   **** *   
 4      *  * *    **  
 5    *  *   *****  * 
 6 ** *     *    *** *
 7    * ***       *  *
 8               **** 
 9 *         ******   
10* *          *      
11   *  *      **   * 
12**    ****       ***
13  *         *** ** *
14      *  *   *   ***
15 **   ***      ** **
16      *         * **
17                    
18                    
19            
Functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
boolMatrix::boolMatrix()
{
	for (int row = 0; row < NUM_ROWS; row++) {
		for (int col = 0; col < NUM_COLS; col++) {

			 array[row][col] = {false};
		}
	}
}



void boolMatrix::print()
{
	cout << setw(3);
	for (int col = 0; col < NUM_ROWS - 10; col++) {
		cout << col;
	}
	for (int col = 0; col < NUM_ROWS - 10; col++) {
		cout << col;
	}
	cout << endl;
	
	for (int row = 0; row < NUM_ROWS; row++) {
		cout << setw(2);
		cout << row;
		for (int col = 0; col < NUM_COLS; col++) {

			if (array[row][col] == false) {
				cout << " ";
			}
			else cout << "*";
		}
		cout << endl;
	}
	
}
Last edited on
I should add that I am not allowed to have any arrays in main.
You could make your ctor do something like.

array[row][col] = rand() % 100 > 50; // > gives you a boolean true/false
That works good.

Is that read as, if a random number divided by 100 has a remainder greater than 50, then true. Otherwise false?
Last edited on
Well a random number modulo 100.
Thus giving you values in the range 0 to 99.

So in fact > is the wrong test, as it's slightly biased towards false.
Ok thank you.
Do you want your true/false distribution to be even, or do you want a bias towards false or true?

Using one of the C++ random engines (std::default_random_engine for example) and the std::bernoulli_distribution generates boolean values.

http://www.cplusplus.com/reference/random/bernoulli_distribution/

(the above example won't generate truly random boolean values, the engine is not properly seeded)

It will require a C++11 or later compiler to work.
Last edited on
Topic archived. No new replies allowed.