解决Lisp中的河内递归塔 [英] Solving recursive Towers of Hanoi in Lisp

查看:184
本文介绍了解决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

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

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

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中的河内递归塔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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