Fill matrix with binary numbers, regular and gray

2019-03-04 08:03发布

问题:

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

回答1:

You can get gray code by simply changing

Integer.toBinaryString(r)

into

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

Have a try:)



回答2:

This should do it:

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

EDIT: WORKS ONLY FOR grayCodeLength < Integer.SIZE