Gangmax Blog

Ruby版本的“汉诺塔(Hanoi)”程序

Migarated from here at ‘2012-06-04 17:16:25’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def hanoi(n, from, to, temp)
if(n<=0)
puts "n should be a positive integer."
elsif(n==1)
move(n, from, to)
else
hanoi(n-1, from, temp, to)
move(n, from, to)
hanoi(n-1, temp, to, from)
end
end

def move(n, from, to)
puts "Move No.#{n} disk from #{from} to #{to}."
end

hanoi(5, "Start", "Finish", "Temp")

Comments