Towers of Hanoi: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Recursion moved to Towers of Hanoi: Towers of Hanoi is an excellent application of Recursion, but it does not necessarily exemplify it.)
(Added Java section)
Line 17: Line 17:
return moves
return moves
end hanoi
end hanoi


==[[Java]]==
[[Category:Java]]

public void move(int n, int from, int to, int via) {
if (n == 1) {
System.out.println("Move disk from pole " + from + " to pole " + to);
} else {
move(n - 1, from, via, to);
move(1, from, to, via);
move(n - 1, via, to, from);
}
}


==[[Python]]==
==[[Python]]==

Revision as of 17:16, 30 January 2007

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

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

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


Java

 public void move(int n, int from, int to, int via) {
   if (n == 1) {
     System.out.println("Move disk from pole " + from + " to pole " + to);
   } else {
     move(n - 1, from, via, to);
     move(1, from, to, via);
     move(n - 1, via, to, from);
   }
 }

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)