填写矩阵二进制数,定期和灰色codeD矩阵、灰色、二进制数、codeD

2023-09-11 02:43:32 作者:我是贱人爱过烂人i

我有一个矩阵,持有1:s或0:S,创建二进制数。其宽度为n。对于n = 2和n = 3会是这样的:

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

等。现在,我用下面的code产生这种。

  INT行=(int)的Math.pow(2,N);
INT COL = N;
INT [] []矩阵=新INT [行] [COL];
对于(INT R = 0; R<排; R ++){
    串binaryNumber =的String.Format(%+ N +的s,Integer.toBinaryString(r)的)代替('','0')。
    对于(INT C = COL  -  1; C> = 0; C--){
        矩阵[R] [C] =的Integer.parseInt(+ binaryNumber.charAt(0));
        binaryNumber = binaryNumber.substring(1);
    }
}
 

现在我需要创建同样的事情,但灰度codeD帮助。有没有一种简便的方法来做到这一点在Java中?此外,如果有一个更聪明的方法做我在做什么上面我很想学习。

我真的没有一个线索从哪里开始,因为我已经习惯了有 toBinaryString()帮助我。编辑:灰度code将是这样的:

  00 000
01 001
11 011
10 010
    110
    111
    101
    100
 
C语言基础 1.比特位与字节的关系,二进制 八进制 十六进制之间的转换,内存为什么使用十六进制

解决方案

您可以通过简单地改变得到灰色code

Integer.toBinaryString(R)

Integer.toBinaryString((R>> 1)^ R)。

有一个尝试:)

I have a matrix that holds 1:s or 0:s, creating binary numbers. Its width is n. For n = 2 and n = 3 it would look like:

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

and so on. Right now I'm using the following code to produce this.

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

Now I need help with creating the same thing but gray-coded. Is there a convenient way to do this in java? Also, if there is a smarter way to do what I'm doing above I'd love to learn.

I don't really have a clue where to start since I'm used to having toBinaryString() helping me. EDIT: The gray-code will look like this:

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

解决方案

You can get gray code by simply changing

Integer.toBinaryString(r)

into

Integer.toBinaryString((r >> 1) ^ r).

Have a try:)