Creating a Binary Matrix with C++ Code

Click For Summary
SUMMARY

This discussion focuses on creating a binary matrix in C++ that represents all possible combinations of binary entries for a given number of columns, n. The total number of combinations is calculated as 2^n. A sample output for n=3 is provided, showing the binary matrix with eight different rows. The suggested approach involves looping through integers from 0 to (2^n - 1) and printing their bits, utilizing bitwise operations to generate the matrix efficiently.

PREREQUISITES
  • Understanding of C++ programming language
  • Familiarity with bitwise operations
  • Knowledge of loops and conditional statements in C++
  • Basic concepts of binary representation
NEXT STEPS
  • Implement and test the provided C++ code for generating binary matrices
  • Explore optimization techniques for handling larger values of n in C++
  • Learn about alternative methods for generating combinations, such as recursive algorithms
  • Investigate memory management in C++ for large binary matrices
USEFUL FOR

C++ developers, computer science students, and anyone interested in algorithm design and binary data representation.

jetoso
Messages
73
Reaction score
0
I want to build a binary matrix (with 1 and 0 entries) with all possible combinations, say for example if n is the number of entries of one row of the matrix, then 2^n is the total number of different entries in the matrix.

For instance, for n=3, 2^n = 8, so we would have the following matrix
[ 1 0 0
0 1 0
0 0 1
1 1 0
1 0 1
0 1 1
1 1 1
0 0 0 ]

I am writing a C++ code but I have not figured out how to make it. Any suggestions?
 
Last edited by a moderator:
Technology news on Phys.org
Do you plan to go beyond n = 32? If so, I don't think the project is practical. If not, then you can simply loop through the integers from 0 to (2^n - 1) and print out their bits. I haven't tried this code, but it might work. If the order of the lines matters, then you can manipulate things as needed.

Code:
// print the bit patterns for the first 2^n integers
for (int wRow = 0; wRow < (2^n); ++wRow)
{
  // make a copy of the row number
  int wBitMap = wRow;

  // for each bit
  for (int wBit = 0; wBit < n; ++wBit)
  {
    // display the leftmost bit along with a space character
    cout << wBitMap & 1 << " ";
    // and shift a new bit into place
    wBitMap /= 2;
  }
  cout << endl;
}
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 25 ·
Replies
25
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
1
Views
1K
  • · Replies 17 ·
Replies
17
Views
4K
  • · Replies 9 ·
Replies
9
Views
3K
Replies
9
Views
3K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 2 ·
Replies
2
Views
3K