Towers of Hanoi

Revision as of 19:25, 26 January 2007 by MikeMol (talk | contribs) (Recursion moved to Towers of Hanoi: Towers of Hanoi is an excellent application of Recursion, but it does not necessarily exemplify it.)

In this task, the goal is to solve the Towers of Hanoi problem with recursivity.

Task
Towers of Hanoi
You are encouraged to solve this task according to the task description, using any language you may know.

AppleScript

global moves --this is so the handler 'hanoi' can see the 'moves' variable
set moves to ""
hanoi(4, "peg A", "peg C", "peg B")

on hanoi(ndisks, fromPeg, toPeg, withPeg)
    if ndisks is greater than 0 then
        hanoi(ndisks - 1, fromPeg, withPeg, toPeg)
        set moves to moves & "Move disk " & ndisks & " from " & fromPeg & " to " & toPeg & return
        hanoi(ndisks - 1, withPeg, toPeg, fromPeg)
    end if
    return moves
end hanoi

Python

def hanoi(ndisks, startPeg=1, endPeg=3):
  if ndisks:
    hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
    print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg)
    hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)

hanoi(ndisks=4)