Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Another recursive question

800147Mar 25 2011 — edited Mar 30 2011
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.
This post has been answered by 796440 on Mar 30 2011
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 27 2011
Added on Mar 25 2011
41 comments
857 views