-- -- $Header: /Users/dap/lua/RCS/Hanoi.lua,v 1.5 2007/02/11 08:49:51 dap Exp $ -- -- Hanoi - Towers of Hanoi diversion -- -- Author (a) 2007, Damon A Permezel. All bugs revered. -- module(..., package.seeall) OO=require"OO" local Hanoi = OO.class { __name = "Hanoi base class", MAX_RINGS = 9, nRings = 3, } -- -- init - initialise a Hanoi object instance -- function Hanoi:init() if 0 >= self.nRings or self.nRings > Hanoi.MAX_RINGS then error(('funny number of rings: %d'):format(self.nRings)) end end -- -- run - perform the Towers of Hanoi algorithm -- function Hanoi:run() self:hanoi(self:reset()) end -- -- hanoi - the guts of the algorithm -- -- Input: -- n # of rings -- from pole to move from -- to pole to move to -- work pole to aid in performing work -- function Hanoi:hanoi(n, from, to, work) if n > 0 and not self.stop then self:hanoi(n-1, from, work, to) self:moveRing(n, from, to) self:hanoi(n-1, work, to, from) end end -- -- moveRing - default method to move ring -- -- Override this with something more interesting! -- function Hanoi:moveRing(n, from, to) print(("move ring %3d from %8s to %8s"):format(n, from, to)) end -- -- reset - default reset method -- -- Override this with what your moveRing needs.... -- function Hanoi:reset() return self.nRings, 'A', 'B', 'C' end return Hanoi