#! /usr/bin/env ruby # Towers of Hanoi # Copyright (C) 2000 by Michael Neumann (neumann@s-direktnet.de) # This is public domain. # class Towers_of_Hanoi A = 0; B = 1; C = 2 def initialize(n) # n = number of stack-elements of the tower @n = n @stack = [] @stack[A] = (1..@n).to_a.reverse # from @stack[B] = [] # to @stack[C] = [] # help end # # "from" and "to" are integers A,B or C. # n is the number of elements to put from stack "from" # to stack "to" counted from the top of the stack # def move(from, to, n) if n == 1 then @stack[to].push(@stack[from].pop) output elsif n > 1 then help = ([A,B,C] - [from,to])[0] # get help-stack move(from, help, n-1) move(from, to, 1) move(help, to, n-1) end end # # run the simulation # def run output move(A, B, @n) end # # override this method for user-defined output # def output p @stack end private :output end # # test-program # if __FILE__ == $0 print "Towers of Hanoi\n" print "---------------\n" print "Please input the height of the tower (e.g. 5): " n = readline.to_i toh = Towers_of_Hanoi.new(n) # # prints the three stacks out # and waits for keypress # def toh.output for i in 0..2 do print "abc"[i].chr, ": " p @stack[i] end readline end toh.run end