Fill matrix with binary numbers, regular and gray coded

故事扮演 提交于 2019-12-02 08:03:05

You can get gray code by simply changing

Integer.toBinaryString(r)

into

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

Have a try:)

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!