It a solution to the Towers of Hanoi for an arbitrary number of disks that utilizes the concept of recursion. The solution it generates is the absolute minimum number of moves for a given number of disks. It was a little different when written in VAX BASIC because VAX BASIC supports local data spaces for subroutines and hence allows for true recursion. I re-wrote it for MBASIC and implemented the recursion through using a temporary variable and shifting values around before and after the recursive calls (to line 190).
In the following code T is the temporary variable. S is the source tower, D is the destination tower. See if you can figure out how it works.. and have some fun.
- Code: Select all
10 FOR X=0 TO 20:PRINT:NEXT X
20 PRINT "*********************"
30 PRINT "* *"
40 PRINT "* TOWERS OF HANOI *"
50 PRINT "* *"
60 PRINT "*********************"
70 PRINT
75 K=0
80 INPUT "NUMBER OF DISKS";J
90 S=1:B=2:D=3:N=J+1
100 GOSUB 190
105 PRINT K;" MOVES REQUIRED"
110 END
190 N=N-1
200 IF N=1 THEN GOSUB 300:GOTO 240
210 T=B:B=D:D=T:GOSUB 190:T=D:D=B:B=T:N=N+1
220 GOSUB 300
230 T=S:S=B:B=T:GOSUB 190:T=B:B=S:S=T:N=N+1
240 RETURN
300 PRINT "MOVE";S;"TO";D;
305 K=K+1
315 PRINT
320 RETURN