【问题标题】:How to generate combinations of 0's and 1's in a 1024X 10 Matrix如何在 1024X 10 矩阵中生成 0 和 1 的组合
【发布时间】:2016-04-18 22:27:24
【问题描述】:

我必须在矩阵中生成所有可能的 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++;
                                        }
                                    }
                                }
                            }

【问题讨论】:

  • 你认为什么是“组合”?
  • 您是否需要“查找”或“生成”组合(——无论您使用“组合”这个词是什么意思)?
  • 我需要生成组合
  • @MouseEvent 通过组合我的意思是 0000000000, 0000000001, 0000000010,0000000011....等
  • 最好的办法是使用整数并将它们转换为二进制。见:stackoverflow.com/questions/5263187/…

标签: java arrays matrix combinations


【解决方案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 &lt;&lt; 10 等于 210 或 1024。这就解释了 1 &lt;&lt; BITS

要了解(i &gt;&gt; (BITS-1 - j)) &amp; 1,让我们看一些示例值。假设i == 673 或二进制的1010100001。假设j == 2 表示我们想要左边的第三位。替换所有变量,我们有:

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

班次是673 &gt;&gt; 10-1 - 2,或673 &gt;&gt; 7。将1010100001 向右移动 7 个位置会切断最右边的 7 个位,得到101<strike>0100001</strike>。看看我们想要的位现在是最右边的位了吗?最后的&amp; 1 提取最右边的位,所以我们得到1 作为最终结果。作业结束为:

connectMat[673][2] = 1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 2011-04-28
    • 2020-01-15
    • 1970-01-01
    相关资源
    最近更新 更多