Hi,
I am trying to make a program that generates n-bit Gray code. The reflected binary code, also known as Gray code, is a binary numeral system where two successive values differ in only one bit.
Another explanation would be - an n-bit Gray code is a list of the 2^n different n-bit binary numbers such that each entry in the list differs in precisely one bit from its predecessor.
If I want to generate 1-bit gray code that would be:
*0*
*1*
2-bits would be:
*0 0*
*0 1*
*1 1*
*1 0*
3-bits would be:
*0 0 0*
*0 0 1*
*0 1 1*
*0 1 0*
*1 1 0*
*1 1 1*
*1 0 1*
*1 0 0*
and so on.
This is what I have so far:
public class GrayCode {
static void genGC(int n){
if(n == 0){
System.out.println(n);
}
else{
genGC(n-1);
genGC(n-1);
}
}
public static void main(String[] args) {
int a = 1;
genGC(a);
}
}
So, in the case of 1-bit gray code the above program would output:
*0*
*0*
for 2-bits code:
*0*
*0*
*0*
*0*
etc.
Any ideas or hints what to do in order to go further are greatly appreciated.
Thanks in advance.