解决Lisp中的河内递归塔

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

我在Lisp中的代码如下:

My code in lisp is as follows:

(defun solve-hanoi(from) (hanoi (length from) from '() '())) (defun hanoi(height from to aux) (when (>= height 1) (hanoi (- height 1) from aux to) (format t "~%Move ~a from ~a to ~a" (nth 0 from) from to) (push (pop from) to) (hanoi (- height 1) aux to from)))

我对Lisp陌生,对我做错的事情一无所知. 自从我已经花了几个小时了,对此的帮助将不胜感激.

I am new to lisp and have NO clue as to what I am doing wrong. Help with this would be GREATLY appreciated since I've been at this for hours.

谢谢.

推荐答案

递归算法为:

要将n张光盘从钉A移到钉C: 1.将n-1个光盘从A移到B.这将使光盘n独自留在钉A上 2.将光盘n从A移到C 3.将n−1个光盘从B移到C,以便它们位于光盘n上

To move n discs from peg A to peg C: 1. move n−1 discs from A to B. This leaves disc n alone on peg A 2. move disc n from A to C 3. move n−1 discs from B to C so they sit on disc n

(来自 en.wikipedia/wiki/Tower_of_Hanoi#Recursive_solution)

由于A,B和C(您的from,aux和to)的含义相对于当前迭代并不断变化,因此更容易不传递游戏状态并尝试了解其含义,而只是生成解决方案说明.

Since the meaning of A, B and C (your from, aux and to) are relative to the current iteration and keep changing, it's easier not to pass the state of the game around and trying to understand what it means, but to simply generate solving instructions.

要以这种方式实现上述算法,您需要在(when (>= height 1)内添加以下内容: 1.用n-1进行递归调用,交换B和C.您已经正确地做到了这一点. 2.打印有关移动的信息,例如(format t "~%Move ~a to ~a" from to). 3.用n-1进行递归调用,交换A和B.您也正确地做到了这一点.

To implement the algorithm above in this way, you need the following inside your (when (>= height 1): 1. Recursive call with n-1, swapping B and C. You got this one right already. 2. Print info about the move, for instance (format t "~%Move ~a to ~a" from to). 3. Recursive call with n-1, swapping A and B. You got this one right too.

然后更改您的(solve-hanoi),使其以第一个棒上的磁盘数量为参数,并使用该编号以及您想要的棒名称(例如(hanoi 4 'A 'B 'C)或(hanoi 4 1 2 3))调用(hanoi) 4个磁盘.

Then change your (solve-hanoi) so that it takes the number of disks on the first rod as argument, and calls (hanoi) with this number and whatever names you want for the rods, for instance (hanoi 4 'A 'B 'C) or (hanoi 4 1 2 3) for 4 disks.

更多推荐

解决Lisp中的河内递归塔

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

发布评论

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

>www.elefans.com

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