Reputation: 1
I have to generate all the possible combinations of 0's and 1's in the matrix.. Like:
0000000000, 0000000001, 0000000010, 0000000011.... etc.
Is there a better way to do it rather than using nested for loops as shown below?
class Reliability {
// Trying to create combinations of 0 and 1s
public static void main(String[] args) {
// Creating an array of size 1024X10
int connectMat[][] = new int[1024][10];
int count1 = 0;
// Intitially all rows are set to zero
for (int r1 = 0; r1 <= 1; r1++) {
// fill all rows with 0 and the 1
for (int r2 = 0; r2 <= 1; r2++) {
for (int r3 = 0; r3 <= 1; r3++) {
for (int r4 = 0; r4 <= 1; r4++) {
// Updating the elements of each row
connectMat[count1][0] = r1;
connectMat[count1][1] = r2;
connectMat[count1][2] = r3;
connectMat[count1][3] = r4;
// Incrementing count to point to the next row
count1++;
}
}
}
}
Upvotes: 0
Views: 69
Reputation: 361729
This problem translates directly into looking at the binary representation of each row number. We can use bit operations to pull out the necessary values.
final int BITS = 10;
int[][] connectMat = new int[1 << BITS][BITS];
for (int i = 0; i < (1 << BITS); ++i) {
for (int j = 0; j < BITS; ++j) {
connectMat[i][j] = (i >> (BITS-1 - j)) & 1;
}
}
Note that 1 << 10
is equal to 210, or 1024. That explains 1 << BITS
.
To understand (i >> (BITS-1 - j)) & 1
, let's look at some example values. Let's say i == 673
, or 1010100001
in binary. And let's say j == 2
meaning we want the third bit from the left. Replacing all the variables, we have:
connectMat[673][2] = (673 >> (10-1 - 2)) & 1;
The shift is 673 >> 10-1 - 2
, or 673 >> 7
. Shifting 1010100001
to the right 7 places cuts off the seven rightmost bits, giving us 101
. See how the bit we wanted is now the rightmost bit? The final 0100001& 1
extracts the rightmost bit, so we get 1
as the final result. The assignment ends up as:
connectMat[673][2] = 1;
Upvotes: 1