Click here to Skip to main content
15,895,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
public class GrayCode {

// append reverse of order n gray code to prefix string, and print
public static void yarg(String prefix, int n) {
if (n == 0) StdOut.println(prefix);
else {
gray(prefix + "1", n - 1);
yarg(prefix + "0", n - 1);
}
} 

// append order n gray code to end of prefix string, and print
public static void gray(String prefix, int n) {
if (n == 0) StdOut.println(prefix);
else {
gray(prefix + "0", n - 1);
yarg(prefix + "1", n - 1);
}
} 


public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
gray("", n);
}

}


Could someone explain how this code works?

What I have tried:

I've been trying to write method for gray code and my way was very unneficient, many loops and lists. It's a lot better to use recursion and I found this example but I am not realy sure if I know how it works.
Posted
Updated 4-Dec-16 2:15am
v2
Comments
Patrice T 4-Dec-16 3:26am    
What does it output ?
Gray code - Wikipedia[^]

1 solution

The debugger is a great tool to comprehend foreign code.If the output is gray code, then that is what the code is doing. Study Gray code.
Gray code - Wikipedia[^]

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.
Note than listing Gray code is no more complicated than listing binary number in order, it just need to add a small step. recursion is not necessary.
-----
The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900