The classic puzzle using 3 poles and 3 rings of decreasing size.
The objective is to move all 3 rings from the left pole to the far end pole by moving only one ring per turn and only placing a ring onto an empty pole or larger ring.
I found this problem in a computer science book as an example of a recursive function (one that calls itself). The book supplied me with pseudo-code for function so all i had to do was write it up in BASIC and work out how to display it on the screen.
I still don't quite understand the application for recursive functions but it is very clever.
`*** The Towers of Hanoi Problem ***
`I will use binary system to store rings on poles (1=small ring, 2=medium, 4=large)
DIM Pole(3)
Pole(1) = 7 : Pole(2) = 0 : Pole(3) = 0
`setup
hide mouse
sync on
`display the initial puzzle
display()
`call transfer function
Transfer(3, 1, 2, 3)
END
`Transfer
FUNCTION Transfer(N, source, destination, temporary_store)
`Problem Fix Variables
S = source
D = destination
T = temporary_store
If N = 1
Move(S, D)
Else
Transfer(N-1, S, T, D)
Move(S, D)
Transfer(N-1, T, D, S)
Endif
ENDFUNCTION
`Move
FUNCTION Move(source, destination)
`which ring is to be moved?
Select Pole(source)
Case 1 : ring = 1 : Endcase
Case 2 : ring = 2 : Endcase
Case 3 : ring = 1 : Endcase
Case 4 : ring = 4 : Endcase
Case 5 : ring = 1 : Endcase
Case 6 : ring = 2 : Endcase
Case 7 : ring = 1 : Endcase
Endselect
`Take ring from source and add to destination
Pole(source) = Pole(source) - ring
Pole(destination) = Pole(destination) + ring
`Update display
Display()
ENDFUNCTION
`Display
FUNCTION Display()
cls
For x = 1 to 3
`draw poles
ink rgb(120,40,0),0
Line 100+(100*x), 100, 100+(100*x), 200
`disintergrate pole variables
ink rgb(255,200,0),0
pole = Pole(x)
rings = 0
`big ring?
if pole - 4 >=0
inc rings
box 100+(100*x)-40, 183-((rings-1)*20), 100+(100*x)+40, 200-((rings-1)*20)
pole = pole - 4
endif
`medium ring?
if pole - 2 >=0
inc rings
box 100+(100*x)-30, 183-((rings-1)*20), 100+(100*x)+30, 200-((rings-1)*20)
pole = pole - 2
endif
`small ring?
if pole - 1 >=0
inc rings
box 100+(100*x)-20, 183-((rings-1)*20), 100+(100*x)+20, 200-((rings-1)*20)
pole = pole - 1
endif
Next x
sync
wait 1000
ENDFUNCTION