如何在递归java中编写灰色代码 [英] How do I write gray code in recursion java

查看:119
本文介绍了如何在递归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.

推荐答案

调试器是一个很好的理解工具外部代码。如果输出是格雷码,那么这就是代码正在做的事情。学习格雷码。

格雷码 - 维基百科 [ ^ ]



你应该学会使用调试器尽快。而不是猜测你的代码在做什么,现在是时候看到你的代码正在执行并确保它完成你所期望的。

注意比列出格雷码并不比按顺序列出二进制数复杂,它只需要添加一小步。递归是没有必要的。

-----

调试器允许你逐行跟踪执行,检查变量,你会看到有一个点它停止做你期望的事。

调试器 - 维基百科,免费的百科全书 [ ^ ]

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 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.


这篇关于如何在递归java中编写灰色代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆