Search code examples
javaalgorithmmatrixbinarygray-code

Fill matrix with binary numbers, regular and gray coded


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

Solution

  • You can get gray code by simply changing

    Integer.toBinaryString(r)

    into

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

    Have a try:)