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.
解决方案
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.