开发者

Solving recursive Towers of Hanoi in Lisp

开发者 https://www.devze.com 2023-04-12 10:43 出处:网络
My code in lisp is as follows: (defun solve-hanoi(from) (hanoi (length from) from \'() \'())) (defun hanoi(height from to aux) (when (>= height 1)

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 t开发者_高级运维o)
                   (push (pop from) to) 
                   (hanoi (- height 1) aux to from)))

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.

Thanks.


The recursive algorithm is:

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

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

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.

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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号