Jump to content

Towers of Hanoi: Difference between revisions

add Tiny BASIC
(Add MAD)
(add Tiny BASIC)
Line 5,403:
End
</lang>
 
=={{header|Tiny BASIC}}==
Tiny BASIC does not have recursion, so only an iterative solution is possible... and it has no arrays, so actually keeping track of individual discs is not feasible.
 
But as if by magic, it turns out that the source and destination pegs on iteration number n are given by (n&n-1) mod 3 and ((n|n-1) + 1) mod 3 respectively, where & and | are the bitwise and and or operators. Line 40 onward is dedicated to implementing those bitwise operations, since Tiny BSIC hasn't got them natively.
 
<lang tinybasic> 5 PRINT "How many discs?"
INPUT D
IF D < 1 THEN GOTO 5
IF D > 10 THEN GOTO 5
LET N = 1
10 IF D = 0 THEN GOTO 20
LET D = D - 1
LET N = 2*N
GOTO 10
20 LET X = 0
30 LET X = X + 1
IF X = N THEN END
GOSUB 40
LET S = S - 3*(S/3)
GOSUB 50
LET T = T + 1
LET T = T - 3*(T/3)
PRINT "Move disc on peg ",S+1," to peg ",T+1
GOTO 30
40 LET B = X - 1
LET A = X
LET S = 0
LET Z = 2048
45 LET C = 0
IF B >= Z THEN LET C = 1
IF A >= Z THEN LET C = C + 1
IF C = 2 THEN LET S = S + Z
IF A >= Z THEN LET A = A - Z
IF B >= Z THEN LET B = B - Z
LET Z = Z / 2
IF Z = 0 THEN RETURN
GOTO 45
50 LET B = X - 1
LET A = X
LET T = 0
LET Z = 2048
55 LET C = 0
IF B >= Z THEN LET C = 1
IF A >= Z THEN LET C = C + 1
IF C > 0 THEN LET T = T + Z
IF A >= Z THEN LET A = A - Z
IF B >= Z THEN LET B = B - Z
LET Z = Z / 2
IF Z</lang>
 
{{out}}<pre>
How many discs?
4
Move disc on peg 1 to peg 3
Move disc on peg 1 to peg 2
Move disc on peg 3 to peg 2
Move disc on peg 1 to peg 3
Move disc on peg 2 to peg 1
Move disc on peg 2 to peg 3
Move disc on peg 1 to peg 3
Move disc on peg 1 to peg 2
Move disc on peg 3 to peg 2
Move disc on peg 3 to peg 1
Move disc on peg 2 to peg 1
Move disc on peg 3 to peg 2
Move disc on peg 1 to peg 3
Move disc on peg 1 to peg 2
Move disc on peg 3 to peg 2
</pre>
 
=={{header|Toka}}==
781

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.