计划中的河内塔(递归)

编程入门 行业动态 更新时间:2024-10-23 08:25:13
本文介绍了计划中的河内塔(递归)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我今天在scheme中编写了以下代码,但是评估是错误的.请不要告诉我我很喜欢编程,我知道这是一个经典的递归问题,但是我遇到了麻烦:

I wrote the following code in scheme today, but the evaluation is wrong. Please don't tell me I suck at programming, I understand that this is a classic recursion problem, but I am having trouble with it:

(define (towers-of-hanoi n source temp dest) (if (= n 1) (begin (display "Move the disk from ") (display source) (display " to " ) (display dest) (newline)) (begin (towers-of-hanoi (- n 1) source temp dest) (display "Move the disk from ") (display source) (display " to ") (display dest) (newline) (towers-of-hanoi(- n 1) temp source dest))))

我希望代码能正常工作,并且在调试它时,我会让自己更加困惑.谁能帮我吗?

I expected the code to work, and when I debug it I just confuse myself even more. Can anyone help me?

推荐答案

在您的代码中,最后一个递归调用似乎是错误的,并且该过程的参数顺序存在问题.尝试以下方法:

In your code, the last recursive call appears to be wrong, and there is a problem with the order of the procedure's parameters. Try this instead:

(define (towers-of-hanoi n source dest temp) (if (= n 1) (begin (display "Move the disk from ") (display source) (display " to " ) (display dest) (newline)) (begin (towers-of-hanoi (- n 1) source temp dest) (display "Move the disk from ") (display source) (display " to ") (display dest) (newline) (towers-of-hanoi (- n 1) temp dest source))))

我注意到您一直在问标记为racket的问题,这是针对Racket的同一代码的更惯用和简短的版本:

I noticed that you've been asking questions tagged as racket, here's a more idiomatic and shorter version of the same code, for Racket:

(define (towers-of-hanoi n source dest temp) (cond [(= n 1) (printf "Move the disk from ~a to ~a~n" source dest)] [else (towers-of-hanoi (sub1 n) source temp dest) (printf "Move the disk from ~a to ~a~n" source dest) (towers-of-hanoi (sub1 n) temp dest source)]))

无论哪种方式,它都能按预期工作:

Either way, it works as expected:

(towers-of-hanoi 3 "source" "dest" "temp") Move the disk from source to dest Move the disk from source to temp Move the disk from dest to temp Move the disk from source to dest Move the disk from temp to source Move the disk from temp to dest Move the disk from source to dest

更多推荐

计划中的河内塔(递归)

本文发布于:2023-11-30 03:11:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648529.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   河内   计划

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!