2016-04-18 39 views
0

我不得不產生矩陣0的所有可能的組合和1 ..我愛:如何產生的1024×10矩陣0的組合和1

0000000000, 0000000001, 0000000010, 0000000011.... etc. 

有沒有更好的方式來做到這一點而不是使用如下所示的嵌套for循環?

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++; 
             } 
            } 
           } 
          } 
+0

你認爲什麼是「組合」? – Mordechai

+0

您是否需要「查找」或「生成」組合( - 無論您對「組合」這個詞是什麼意思)? – Mordechai

+0

我需要生成組合 – Connors

回答

1

該問題直接轉化爲查看每行號的二進制表示。我們可以使用位操作來提取必要的值。

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; 
    } 
} 

注意1 << 10等於2 ,或1024這解釋1 << BITS

要了解(i >> (BITS-1 - j)) & 1,我們來看看一些示例值。我們假設用二進制表示i == 6731010100001。我們假設j == 2意味着我們需要從左邊開始的第三位。更換所有的變量,我們有:

connectMat[673][2] = (673 >> (10-1 - 2)) & 1; 

的轉變是673 >> 10-1 - 2,或673 >> 7。將1010100001向右移7個位置切斷最右邊的7位,給我們101 0100001 。看看我們想要的東西現在是最右邊的位了嗎?最後& 1提取最右邊的位,所以我們得到1作爲最終結果。作業結束爲:

connectMat[673][2] = 1;