Added Lua towers_of_hanoi example
[langlearn/.git] / towers_of_hanoi / lua / MaximumGeeker / hanoi_stack.lua
1 --[[ Towers of hanoi - Lua 5.1 ]]--
2
3 local leftStack, centerStack, rightStack = {name = 'Left'}, {name = 'Center'}, {name = 'Right'}
4
5 local visualize = function(...)
6   local z = {...}
7
8   for i = 1, 3 do
9     print(string.format("%s:\t%s", z[i].name, table.concat(z[i], ' ')))
10   end
11   print()
12 end
13
14 local move = function(a, b)
15   print( a.name, '->', b.name )
16   table.insert( b, table.remove(a) )
17
18   coroutine.yield(true)
19 end
20
21 local hanoi
22 hanoi = function(n, orig, pivot, dest)
23   if n < 1 then
24     return
25   end
26
27   if n == 1 then
28     move( orig, dest )
29     return
30   end
31
32   if n == 2 then
33     move( orig, pivot )
34     move( orig, dest )
35     move( pivot, dest )
36     return
37   end
38
39   hanoi(n-2, orig, pivot, dest)
40   move( orig, pivot )
41   hanoi(n-2, dest, orig, pivot)
42   move( orig, dest )
43   hanoi(n-1, pivot, orig, dest)
44 end
45
46 io.write "Value of N: "
47 local n = tonumber( io.read "*l", 10 )
48
49 if type(n) == 'number' then
50   n = math.floor(n)
51 else
52   io.stderr "Value given is not a number.\n"
53   os.exit(1)
54 end
55
56 for i = n, 1, -1 do
57   leftStack[ #leftStack+1 ] = i
58 end
59
60 local hanoiInteractive = coroutine.wrap(hanoi)
61 local counter = 0
62
63 repeat
64   print('#'..counter..': ')
65   counter = counter + 1
66   visualize( leftStack, centerStack, rightStack )
67   io.read()
68 until hanoiInteractive(n, leftStack, centerStack, rightStack) ~= true