【问题标题】:Fill matrix with binary numbers, regular and gray coded用二进制数填充矩阵,常规和格雷编码
【发布时间】:2013-07-15 10:52:31
【问题描述】:

我有一个包含 1:s 或 0:s 的矩阵,创建二进制数。它的宽度是 n。对于 n = 2 和 n = 3,它看起来像:

00  000
01  001
10  010
11  011
    100
    101
    110
    111

等等。现在我正在使用以下代码来生成它。

int row = (int) Math.pow(2, n);
int col = n;
int[][] matrix = new int[row][col];
for (int r = 0; r < row; r++) {
    String binaryNumber = String.format("%" + n + "s", Integer.toBinaryString(r)).replace(' ', '0');
    for (int c = col - 1; c >= 0; c--) {
        matrix[r][c] = Integer.parseInt("" + binaryNumber.charAt(0));
        binaryNumber = binaryNumber.substring(1);
    }
}

现在我需要帮助来创建相同但灰色编码的东西。在java中有没有方便的方法来做到这一点?另外,如果有更聪明的方法来做我上面所做的事情,我很乐意学习。

我真的不知道从哪里开始,因为我已经习惯了 toBinaryString() 帮助我。编辑:格雷码将如下所示:

00  000
01  001
11  011
10  010
    110
    111
    101
    100

【问题讨论】:

    标签: java algorithm matrix binary gray-code


    【解决方案1】:

    只需更改即可获得格雷码

    Integer.toBinaryString(r)

    进入

    Integer.toBinaryString((r &gt;&gt; 1) ^ r).

    试一试:)

    【讨论】:

    • @mmirwaldt 我不明白你的评论。你能解释更多吗?我只是强调获得格雷码的方法,即(r &gt;&gt; 1) ^ r
    • Integer.toBinaryString 返回一个字符串而不是一个 int(除非你重新解析它)。如果山羊猫只要求格雷码转换,你的回答就足够了。我以为 Goatcat 需要一个不重新解析字符串的格雷码位矩阵。
    • @mmirwaldt 哦,我明白了..:)
    【解决方案2】:

    应该这样做:

    public class GrayCodeMatrix {
        public static void main(String[] args) {
            // set length (< Integer.SIZE)
            final int grayCodeLength = 4;
    
            // generate matrix
            final int grayCodeCount = 1 << grayCodeLength; // = 2 ^ grayCodeLength
            int grayCodeMatrix[][] = new int[grayCodeCount][grayCodeLength];
            for (int i = 0; i < grayCodeCount; i++) {
                int grayCode = (i >> 1) ^ i;
                for (int j = grayCodeLength-1; j >= 0; j--) {
                    // extract bit
                    final int grayCodeBitMask = 1 << j;
                    grayCodeMatrix[i][j] = (grayCode & grayCodeBitMask) >> j;
                }
            }
    
            // view result
            for (int y = 0; y < grayCodeMatrix.length; y++) {
                for (int x = 0; x < grayCodeMatrix[0].length; x++) {
                    System.out.print(grayCodeMatrix[y][x]);
                }
                System.out.print("\n");
            }
        }
    }   
    

    编辑:仅适用于 grayCodeLength

    【讨论】:

    • 感谢您的回答。它帮助我更好地理解:)
    • @mmirwaldt 看看这个问题...stackoverflow.com/questions/17912363/…
    • 感谢您提供该链接。这个解决方案比我的更通用。我的解决方案必须使用 BigInteger 才能更通用。
    猜你喜欢
    • 2014-05-31
    • 1970-01-01
    • 2011-07-05
    • 2015-09-26
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    相关资源
    最近更新 更多