2013-12-05 2 views
2

Я написал следующий код в схеме сегодня, но оценка неверна. Пожалуйста, не говори мне, что я сосу при программировании, я понимаю, что это классическая проблема рекурсии, но у меня возникли проблемы с ним:Башни Ханоя в схеме (рекурсивный)

(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)))) 

Я ожидал, что код для работы, и когда я его отладки я просто путайте себя еще больше. Может кто-нибудь мне помочь?

+0

Я нашел следующие полезные страницы, которые говорят о башни Ханоя через мои собственные исследования и, глядя на другие посты на этом сайте о башнях: http://en.wikipedia.org/ wiki/Tower_of_Hanoi # Рекурсивный% 5Fsolution http://www.cs.cmu.edu/~cburch/survey/recurse/hanoiimpl.html http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/ 13/hanoi.html –

ответ

4

В вашем коде последний рекурсивный вызов представляется неправильным, и существует проблема с порядком параметров процедуры. Попробуйте вместо этого:

(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, вот более идиоматический и сокращенный вариант той же коду, для Ракетки:

(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)])) 

В любом случае, это работает, как ожидалось:

(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 

 Смежные вопросы

  • Нет связанных вопросов^_^