The Towers of Hanoi in Ruby
1 2 # based on: The shortest and "mysterious" TH algorithm, 3 # http://hanoitower.mkolar.org/shortestTHalgo.html 4 # 5 # Further references: 6 # - http://en.wikipedia.org/wiki/Tower_of_Hanoi 7 # - http://hanoitower.mkolar.org/HTonWebE.html 8 # - http://www.google.com/search?q=towers%20of%20hanoi%20Apostolos%20Syropoulos 9 # - http://www.kernelthread.com/hanoi/ 10 # - http://www.kernelthread.com/hanoi/html/rb.html 11 12 n = 5 13 x = 1 14 15 ar = [] 16 17 start_time = Time.now 18 19 while x < (1 << n) 20 fr=(x&x-1)%3; 21 to=((x|x-1)+1)%3; 22 ar.push(fr,to) 23 puts "move from pole #{fr} to pole #{to}" 24 x += 1 25 end 26 27 p ar 28 29 p Time.now - start_time