Towers of Hanoi: Difference between revisions

→‎{{header|Imp77}}: added tested output
m (→‎Python Graphic: (Updated a type comment))
(→‎{{header|Imp77}}: added tested output)
(153 intermediate revisions by 58 users not shown)
Line 6:
Solve the   [[wp:Towers_of_Hanoi|Towers of Hanoi]]   problem with recursion.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F hanoi(ndisks, startPeg = 1, endPeg = 3) -> Void
I ndisks
hanoi(ndisks - 1, startPeg, 6 - startPeg - endPeg)
print(‘Move disk #. from peg #. to peg #.’.format(ndisks, startPeg, endPeg))
hanoi(ndisks - 1, 6 - startPeg - endPeg, endPeg)
 
hanoi(ndisks' 3)</syntaxhighlight>
 
{{out}}
<pre>
Move disk 1 from peg 1 to peg 3
Move disk 2 from peg 1 to peg 2
Move disk 1 from peg 3 to peg 2
Move disk 3 from peg 1 to peg 3
Move disk 1 from peg 2 to peg 1
Move disk 2 from peg 2 to peg 3
Move disk 1 from peg 1 to peg 3
</pre>
 
=={{header|360 Assembly}}==
{{trans|PL/I}}
<langsyntaxhighlight lang="360asm">* Towers of Hanoi 08/09/2015
HANOITOW CSECT
USING HANOITOW,R12 r12 : base register
Line 80 ⟶ 102:
STACKLEN EQU *-STACKDS
YREGS
END HANOITOW</langsyntaxhighlight>
{{out}}
<pre style="height:18ex">
Line 98 ⟶ 120:
14 Move disc from pole 1 to pole 2
15 Move disc from pole 3 to pole 2
</pre>
 
=={{header|6502 Assembly}}==
{{works with|Commodore}}
 
This should work on any Commodore 8-bit computer; just set `temp` to an appropriate zero-page location.
<syntaxhighlight lang="assembly">temp = $FB ; this works on a VIC-20 or C-64; adjust for other machines. Need two bytes zero-page space unused by the OS.
 
; kernal print-char routine
chrout = $FFD2
 
; Main Towers of Hanoi routine. To call, load the accumulator with the number of disks to move,
; the X register with the source peg (1-3), and the Y register with the target peg.
 
hanoi: cmp #$00 ; do nothing if the number of disks to move is zero
bne nonzero
rts
 
nonzero: pha ; save registers on stack
txa
pha
tya
pha
pha ; and make room for the spare peg number
 
; Parameters are now on the stack at these offsets:
count = $0104
source = $0103
target = $0102
spare = $0101
 
; compute spare rod number (6 - source - dest)
tsx
lda #6
sec
sbc source, x
sec
sbc target, x
sta spare, x
 
; prepare for first recursive call
tay ; target is the spare peg
 
tsx
lda source, x ; source is the same
sta temp ; we're using X to access the stack, so save its value here for now
 
lda count, x ; move count - 1 disks
sec
sbc #1
ldx temp ; now load X for call
 
; and recurse
jsr hanoi
 
; restore X and Y for print call
tsx
ldy target, x
lda source, x
tax
 
; print instructions to move the last disk
jsr print_move
 
; prepare for final recursive call
tsx
lda spare, x ; source is now spare
sta temp
lda target, x ; going to the original target
tay
lda count, x ; and again moving count-1 disks
sec
sbc #1
ldx temp
jsr hanoi
 
; pop our stack frame, restore registers, and return
pla
pla
tay
pla
tax
pla
rts
 
; constants for printing
prelude: .asciiz "MOVE DISK FROM "
interlude: .asciiz " TO "
postlude: .byte 13,0
 
; print instructions: move disk from (X) to (Y)
print_move:
pha
txa
pha
tya
pha
 
; Parameters are now on the stack at these offsets:
from = $0102
to = $0101
 
lda #<prelude
ldx #>prelude
jsr print_string
tsx
lda from,x
clc
adc #$30
jsr chrout
lda #<interlude
ldx #>interlude
jsr print_string
tsx
lda to,x
clc
adc #$30
jsr chrout
lda #<postlude
ldx #>postlude
jsr print_string
pla
tay
pla
tax
pla
rts
 
; utility routine: print null-terminated string at address AX
print_string:
sta temp
stx temp+1
ldy #0
loop: lda (temp),y
beq done_print
jsr chrout
iny
bne loop
done_print:
rts</syntaxhighlight>
 
{{Out}}
<pre>MOVE DISK FROM 1 TO 2
MOVE DISK FROM 1 TO 3
MOVE DISK FROM 2 TO 3
MOVE DISK FROM 1 TO 2
MOVE DISK FROM 3 TO 1
MOVE DISK FROM 3 TO 2
MOVE DISK FROM 1 TO 2
MOVE DISK FROM 1 TO 3
MOVE DISK FROM 2 TO 3
MOVE DISK FROM 2 TO 1
MOVE DISK FROM 3 TO 1
MOVE DISK FROM 2 TO 3
MOVE DISK FROM 1 TO 2
MOVE DISK FROM 1 TO 3
MOVE DISK FROM 2 TO 3</pre>
 
=={{header|8080 Assembly}}==
 
<syntaxhighlight lang="8080asm"> org 100h
lhld 6 ; Top of CP/M usable memory
sphl ; Put the stack there
lxi b,0401h ; Set up first arguments to move()
lxi d,0203h
call move ; move(4, 1, 2, 3)
rst 0 ; quit program
;;; Move B disks from C via D to E.
move: dcr b ; One fewer disk in next iteration
jz mvout ; If this was the last disk, print move and stop
push b ; Otherwise, save registers,
push d
mov a,d ; First recursive call
mov d,e
mov e,a
call move ; move(B-1, C, E, D)
pop d ; Restore registers
pop b
call mvout ; Print current move
mov a,c ; Second recursive call
mov c,d
mov d,a
jmp move ; move(B-1, D, C, E) - tail call optimization
;;; Print move, saving registers.
mvout: push b ; Save registers on stack
push d
mov a,c ; Store 'from' as ASCII digit in 'from' space
adi '0'
sta out1
mov a,e ; Store 'to' as ASCII digit in 'to' space
adi '0'
sta out2
lxi d,outstr
mvi c,9 ; CP/M call to print the string
call 5
pop d ; Restore register contents
pop b
ret
;;; Move output with placeholder for pole numbers
outstr: db 'Move disk from pole '
out1: db '* to pole '
out2: db '*',13,10,'$'</syntaxhighlight>
 
{{out}}
 
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
</pre>
 
=={{header|8086 Assembly}}==
 
<syntaxhighlight lang="asm"> cpu 8086
bits 16
org 100h
section .text
mov bx,0402h ; Set up first arguments to move()
mov cx,0103h ; Registers chosen s.t. CX contains output
;;; Move BH disks from CH via BL to CL
move: dec bh ; One fewer disk in next iteration
jz .out ; If this was last disk, just print move
push bx ; Save the registers for a recursive call
push cx
xchg bl,cl ; Swap the 'to' and 'via' registers
call move ; move(BH, CH, CL, BL)
pop cx ; Restore the registers from the stack
pop bx
call .out ; Print the move
xchg ch,bl ; Swap the 'from' and 'via' registers
jmp move ; move(BH, BL, CH, CL)
;;; Print the move
.out: mov ax,'00' ; Add ASCII 0 to both 'from' and 'to'
add ax,cx ; in one 16-bit operation
mov [out1],ah ; Store 'from' field in output
mov [out2],al ; Store 'to' field in output
mov dx,outstr ; MS-DOS system call to print string
mov ah,9
int 21h
ret
section .data
outstr: db 'Move disk from pole '
out1: db '* to pole '
out2: db '*',13,10,'$'</syntaxhighlight>
 
{{out}}
 
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
</pre>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
5 var, disks
var sa
Line 122 ⟶ 418:
disks @ 1 2 3 hanoi cr bye
 
</syntaxhighlight>
</lang>
 
=={{header|ABC}}==
<syntaxhighlight lang="ABC">HOW TO MOVE n DISKS FROM src VIA via TO dest:
IF n>0:
MOVE n-1 DISKS FROM src VIA dest TO via
WRITE "Move disk from pole", src, "to pole", dest/
MOVE n-1 DISKS FROM via VIA dest TO src
 
MOVE 4 DISKS FROM 1 VIA 2 TO 3</syntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 3</pre>
 
=={{header|Action!}}==
{{Trans|Tiny BASIC}}...via PL/M
<syntaxhighlight lang="action!">
;;; Iterative Towers of Hanoi; translated from Tiny BASIC via PL/M
;;;
 
DEFINE NUMBER_OF_DISCS = "4"
 
PROC Main()
 
INT d, n, x
 
n = 1
FOR d = 1 TO NUMBER_OF_DISCS DO
n = n + n
OD
FOR x = 1 TO n - 1 DO
; as with Algol W, PL/M, Action! has bit and MOD operators
Print( "Move disc on peg " )
Put( '1 + ( ( x AND ( x - 1 ) ) MOD 3 ) )
Print( " to peg " )
Put( '1 + ( ( ( x OR ( x - 1 ) ) + 1 ) MOD 3 ) )
PutE()
OD
RETURN
</syntaxhighlight>
{{out}}
<pre>
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|ActionScript}}==
<langsyntaxhighlight lang="actionscript">public function move(n:int, from:int, to:int, via:int):void
{
if (n > 0)
Line 133 ⟶ 499:
move(n - 1, via, to, from);
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
 
procedure Towers is
Line 150 ⟶ 516:
begin
Hanoi(4);
end Towers;</langsyntaxhighlight>
 
=={{header|Agena}}==
<langsyntaxhighlight lang="agena">move := proc(n::number, src::number, dst::number, via::number) is
if n > 0 then
move(n - 1, src, via, dst)
Line 161 ⟶ 527:
end
 
move(4, 1, 2, 3)</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
<syntaxhighlight lang="algol60">begin
procedure movedisk(n, f, t);
integer n, f, t;
begin
outstring (1, "Move disk from");
outinteger(1, f);
outstring (1, "to");
outinteger(1, t);
outstring (1, "\n");
end;
 
procedure dohanoi(n, f, t, u);
integer n, f, t, u;
begin
if n < 2 then
movedisk(1, f, t)
else
begin
dohanoi(n - 1, f, u, t);
movedisk(1, f, t);
dohanoi(n - 1, u, t, f);
end;
end;
 
dohanoi(4, 1, 2, 3);
outstring(1,"Towers of Hanoi puzzle completed!")
end</syntaxhighlight>
{{out}}
<pre>Move disk from 1 to 3
Move disk from 1 to 2
Move disk from 3 to 2
Move disk from 1 to 3
Move disk from 2 to 1
Move disk from 2 to 3
Move disk from 1 to 3
Move disk from 1 to 2
Move disk from 3 to 2
Move disk from 3 to 1
Move disk from 2 to 1
Move disk from 3 to 2
Move disk from 1 to 3
Move disk from 1 to 2
Move disk from 3 to 2
Towers of Hanoi puzzle completed!</pre>
 
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">PROC move = (INT n, from, to, via) VOID:
IF n > 0 THEN
move(n - 1, from, via, to);
Line 174 ⟶ 587:
main: (
move(4, 1,2,3)
)</langsyntaxhighlight>
 
 
COMMENT Disk number is also printed in this code (works with a68g): COMMENT
 
<langsyntaxhighlight lang="algol68">
PROC move = (INT n, from, to, via) VOID:
IF n > 0 THEN
Line 189 ⟶ 602:
move(4, 1,2,3)
)
</syntaxhighlight>
</lang>
 
=={{header|ALGOL-M}}==
<syntaxhighlight lang="algolm">begin
procedure move(n, src, via, dest);
integer n;
string(1) src, via, dest;
begin
if n > 0 then
begin
move(n-1, src, dest, via);
write("Move disk from pole ");
writeon(src);
writeon(" to pole ");
writeon(dest);
move(n-1, via, src, dest);
end;
end;
 
move(4, "1", "2", "3");
end</syntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3</pre>
 
=={{header|ALGOL W}}==
===Recursive===
Following Agena, Algol 68, AmigaE...
<langsyntaxhighlight algolwlang="pascal">begin
procedure move ( integer value n, from, to, via ) ;
if n > 0 then begin
Line 202 ⟶ 652:
move( 4, 1, 2, 3 )
end.</langsyntaxhighlight>
 
===Iterative===
{{Trans|Tiny BASIC}}
<syntaxhighlight lang="pascal">begin % iterative towers of hanoi - translated from Tiny Basic %
integer d, n;
while begin writeon( "How many disks? " );
read( d );
d < 1 or d > 10
end
do begin end;
n := 1;
while d not = 0 do begin
d := d - 1;
n := 2 * n
end;
for x := 1 until n - 1 do begin
integer s, t;
% Algol W has the necessary bit and modulo operators so these are used here %
% instead of implementing them via subroutines %
s := number( bitstring( x ) and bitstring( x - 1 ) ) rem 3;
t := ( number( bitstring( x ) or bitstring( x - 1 ) ) + 1 ) rem 3;
write( i_w := 1, s_w := 0, "Move disc on peg ", s + 1, " to peg ", t + 1 )
end
end.</syntaxhighlight>
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">PROC move(n, from, to, via)
IF n > 0
move(n-1, from, via, to)
Line 215 ⟶ 689:
PROC main()
move(4, 1,2,3)
ENDPROC</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
#proto hanoi(_X_,_Y_,_Z_,_W_)
main:
get arg number (2,discos)
{discos}!neg? do{fail=0,mov(fail),{"I need a positive (or zero) number here, not: ",fail}println,exit(0)}
pos? do{
_hanoi( discos, "A", "B", "C" )
}
exit(0)
.locals
hanoi(discos,inicio,aux,fin)
iif( {discos}eqto(1), {inicio, "->", fin, "\n"};print, _hanoi({discos}minus(1), inicio,fin,aux);\
{inicio, "->", fin, "\n"};print;\
_hanoi({discos}minus(1), aux, inicio, fin))
back
</syntaxhighlight>
{{out}}
<pre>
For 4 discs:
A->B
A->C
B->C
A->B
C->A
C->B
A->B
A->C
B->C
B->A
C->A
B->C
A->B
A->C
B->C
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
 
<syntaxhighlight lang="apl">hanoi←{
move←{
n from to via←⍵
n≤0:⍬
l←∇(n-1) from via to
r←∇(n-1) via to from
l,(⊂from to),r
}
'⊂Move disk from pole ⊃,I1,⊂ to pole ⊃,I1'⎕FMT↑move ⍵
}</syntaxhighlight>
 
{{out}}
 
<pre> hanoi 4 1 2 3
Move disk from pole 1 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">--------------------- TOWERS OF HANOI --------------------
<lang applescript>-- hanoi :: Int -> (String, String, String) -> [(String, String)]
 
-- hanoi :: Int -> (String, String, String) -> [(String, String)]
on hanoi(n, abc)
script go
on |λ|(n, {x, y, z})
if n > 0 then
|λ|(set m to n - 1, {x, z, y}) & ¬
{{x, y}} & |λ|(n - 1, {z, y, x})
|λ|(m, {x, z, y}) & ¬
{{x, y}} & |λ|(m, {z, y, x})
else
{}
Line 230 ⟶ 779:
end |λ|
end script
go's |λ|(n, abc)
end hanoi
 
 
-- TEST ---------------------------------------------------
--------------------------- TEST -------------------------
on run
unlines(map(intercalate(" -> "), ¬
script arrow
on |λ|(abc)
item 1 of abc & " -> " & item 2 of abc
end |λ|
end script
unlines(map(arrow, ¬
hanoi(3, {"left", "right", "mid"})))
end run
 
 
-- GENERIC FUNCTIONS ------------------- GENERIC FUNCTIONS -------------------
 
-- intercalate :: String -> [String] -> String
on intercalate(delim)
script
on |λ|(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set s to xs as text
set my text item delimiters to dlm
s
end |λ|
end script
end intercalate
 
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 259 ⟶ 818:
end if
end mReturn
 
 
-- map :: (a -> b) -> [a] -> [b]
Line 271 ⟶ 831:
end tell
end map
 
 
-- unlines :: [String] -> String
Line 279 ⟶ 840:
set my text item delimiters to dlm
str
end unlines</langsyntaxhighlight>
{{Out}}
<pre>left -> right
Line 288 ⟶ 849:
mid -> right
left -> right</pre>
----
More illustratively:
 
''(I've now eliminated the recursive ''|move|()'' handler's tail calls. So it's now only called 2 ^ (n - 1) times as opposed to 2 ^ (n + 1) - 1 with full recursion. The maximum call depth of n is only reached once, whereas with full recursion, the maximum depth was n + 1 and this was reached 2 ^ n times.)''
 
<syntaxhighlight lang="applescript">on hanoi(n, source, target)
set t1 to tab & "tower 1: " & tab
set t2 to tab & "tower 2: " & tab
set t3 to tab & "tower 3: " & tab
script o
property m : 0
property tower1 : {}
property tower2 : {}
property tower3 : {}
property towerRefs : {a reference to tower1, a reference to tower2, a reference to tower3}
property process : missing value
on |move|(n, source, target)
set aux to 6 - source - target
repeat with n from n to 2 by -1 -- Tail call elimination repeat.
|move|(n - 1, source, aux)
set end of item target of my towerRefs to n
tell item source of my towerRefs to set its contents to reverse of rest of its reverse
set m to m + 1
set end of my process to ¬
{(m as text) & ". move disc " & n & (" from tower " & source) & (" to tower " & target & ":"), ¬
t1 & tower1, ¬
t2 & tower2, ¬
t3 & tower3}
tell source
set source to aux
set aux to it
end tell
end repeat
-- Specific code for n = 1:
set end of item target of my towerRefs to 1
tell item source of my towerRefs to set its contents to reverse of rest of its reverse
set m to m + 1
set end of my process to ¬
{(m as text) & ". move disc 1 from tower " & source & (" to tower " & target & ":"), ¬
t1 & tower1, ¬
t2 & tower2, ¬
t3 & tower3}
end |move|
end script
repeat with i from n to 1 by -1
set end of item source of o's towerRefs to i
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set o's process to {"Starting with " & n & (" discs on tower " & (source & ":")), ¬
t1 & o's tower1, t2 & o's tower2, t3 & o's tower3}
if (n > 0) then tell o to |move|(n, source, target)
set end of o's process to "That's it!"
set AppleScript's text item delimiters to linefeed
set process to o's process as text
set AppleScript's text item delimiters to astid
return process
end hanoi
 
-- Test:
set numberOfDiscs to 3
set sourceTower to 1
set destinationTower to 2
hanoi(numberOfDiscs, sourceTower, destinationTower)</syntaxhighlight>
 
{{Out}}
<pre>"Starting with 3 discs on tower 1:
tower 1: 3, 2, 1
tower 2:
tower 3:
1. move disc 1 from tower 1 to tower 2:
tower 1: 3, 2
tower 2: 1
tower 3:
2. move disc 2 from tower 1 to tower 3:
tower 1: 3
tower 2: 1
tower 3: 2
3. move disc 1 from tower 2 to tower 3:
tower 1: 3
tower 2:
tower 3: 2, 1
4. move disc 3 from tower 1 to tower 2:
tower 1:
tower 2: 3
tower 3: 2, 1
5. move disc 1 from tower 3 to tower 1:
tower 1: 1
tower 2: 3
tower 3: 2
6. move disc 2 from tower 3 to tower 2:
tower 1: 1
tower 2: 3, 2
tower 3:
7. move disc 1 from tower 1 to tower 2:
tower 1:
tower 2: 3, 2, 1
tower 3:
That's it!"</pre>
 
=={{header|ARM Assembly}}==
<syntaxhighlight lang="text">.text
.global _start
_start: mov r0,#4 @ 4 disks,
mov r1,#1 @ from pole 1,
mov r2,#2 @ via pole 2,
mov r3,#3 @ to pole 3.
bl move
mov r0,#0 @ Exit to Linux afterwards
mov r7,#1
swi #0
@@@ Move r0 disks from r1 via r2 to r3
move: subs r0,r0,#1 @ One fewer disk in next iteration
beq show @ If last disk, just print move
push {r0-r3,lr} @ Save all the registers incl. link register
eor r2,r2,r3 @ Swap the 'to' and 'via' registers
eor r3,r2,r3
eor r2,r2,r3
bl move @ Recursive call
pop {r0-r3} @ Restore all the registers except LR
bl show @ Show current move
eor r1,r1,r3 @ Swap the 'to' and 'via' registers
eor r3,r1,r3
eor r1,r1,r3
pop {lr} @ Restore link register
b move @ Tail call
@@@ Show move
show: push {r0-r3,lr} @ Save all the registers
add r1,r1,#'0 @ Write the source pole
ldr lr,=spole
strb r1,[lr]
add r3,r3,#'0 @ Write the destination pole
ldr lr,=dpole
strb r3,[lr]
mov r0,#1 @ 1 = stdout
ldr r1,=moves @ Pointer to string
ldr r2,=mlen @ Length of string
mov r7,#4 @ 4 = Linux write syscall
swi #0 @ Print the move
pop {r0-r3,pc} @ Restore all the registers and return
.data
moves: .ascii "Move disk from pole "
spole: .ascii "* to pole "
dpole: .ascii "*\n"
mlen = . - moves</syntaxhighlight>
 
{{out}}
 
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 3 to pole 1
Move disk from pole 1 to pole 2
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 2 to pole 3
Move disk from pole 3 to pole 1
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 3 to pole 1</pre>
 
=={{header|Arturo}}==
 
{{trans|D}}
 
<syntaxhighlight lang="rebol">hanoi: function [n f dir via][
if n>0 [
hanoi n-1 f via dir
print ["Move disk" n "from" f "to" dir]
hanoi n-1 via dir f
]
]
hanoi 3 'L 'M 'R</syntaxhighlight>
 
{{out}}
 
<pre>Move disk 1 from L to M
Move disk 2 from L to R
Move disk 1 from M to R
Move disk 3 from L to M
Move disk 1 from R to L
Move disk 2 from R to M
Move disk 1 from L to M</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">move(n, from, to, via) ;n = # of disks, from = start pole, to = end pole, via = remaining pole
{
if (n = 1)
Line 303 ⟶ 1,056:
}
}
move(64, 1, 3, 2)</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">Func move($n, $from, $to, $via)
If ($n = 1) Then
ConsoleWrite(StringFormat("Move disk from pole "&$from&" To pole "&$to&"\n"))
Line 316 ⟶ 1,069:
EndFunc
 
move(4, 1,2,3)</langsyntaxhighlight>
 
=={{header|AWK}}==
{{trans|Logo}}
<langsyntaxhighlight AWKlang="awk">$ awk 'func hanoi(n,f,t,v){if(n>0){hanoi(n-1,f,v,t);print(f,"->",t);hanoi(n-1,v,t,f)}}
BEGIN{hanoi(4,"left","middle","right")}'</langsyntaxhighlight>
{{out}}
<pre>left -> right
Line 343 ⟶ 1,096:
{{works with|FreeBASIC}}
{{works with|RapidQ}}
<langsyntaxhighlight lang="freebasic">SUB move (n AS Integer, fromPeg AS Integer, toPeg AS Integer, viaPeg AS Integer)
IF n>0 THEN
move n-1, fromPeg, viaPeg, toPeg
Line 351 ⟶ 1,104:
END SUB
 
move 4,1,2,3</langsyntaxhighlight>
 
===Using <code>GOSUB</code>s===
Here's an example of implementing recursion in an old BASIC that only has global variables:
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|Commodore BASIC}}
{{works with|GW-BASIC}}
<lang gwbasic>10 DIM N(1024), F(1024), T(1024), V(1024): REM STACK PER PARAMETER
{{works with|MSX_BASIC}}
20 SP = 0: REM STACK POINTER
<syntaxhighlight lang="gwbasic">10 DEPTH=4: REM SHOULD EQUAL NUMBER OF DISKS
30 N(SP) = 4: REM START WITH 4 DISCS
20 DIM N(DEPTH), F(DEPTH), T(DEPTH), V(DEPTH): REM STACK PER PARAMETER
40 F(SP) = 1: REM ON PEG 1
5030 T(SP) = 20: REM MOVE TO PEGREM STACK 2POINTER
6040 VN(SP) = 34: REM VIASTART PEGWITH 34 DISCS
50 F(SP) = 1: REM ON PEG 1
70 GOSUB 100
60 T(SP) = 2: REM MOVE TO PEG 2
80 END
70 V(SP) = 3: REM VIA PEG 3
90 REM MOVE SUBROUTINE
80 GOSUB 100
90 END
99 REM MOVE SUBROUTINE
100 IF N(SP) = 0 THEN RETURN
110 OS = SP: REMEMBERREM STORE STACK POINTER
120 SP = SP + 1: REM INCREMENT STACK POINTER
130 N(SP) = N(OS) - 1: REM MOVE N-1 DISCS
Line 382 ⟶ 1,139:
240 GOSUB 100
250 SP = SP - 1 : REM RESTORE STACK POINTER FOR CALLER
260 RETURN</langsyntaxhighlight>
 
===Using binary method===
=={{header|BASIC256}}==
{{works with|Chipmunk Basic}}
<lang BASIC256>call move(4,1,2,3)
{{works with|Commodore BASIC}}
Very fast version in BASIC V2 on Commodore C-64
{{works with|MSX_BASIC}}
<syntaxhighlight lang="gwbasic"> 10 DEF FNM3(X)=X-INT(X/3)*3:REM MODULO 3
20 N=4:GOSUB 100
30 END
99 REM HANOI
100 :FOR M=1 TO 2^N-1
110 ::PRINT MID$(STR$(M),2);":",FNM3(M AND M-1)+1;"TO";FNM3((M OR M-1)+1)+1
130 :NEXT M
140 RETURN</syntaxhighlight>
{{out}}
<pre>1: 1 TO 3
2: 1 TO 2
3: 3 TO 2
4: 1 TO 3
5: 2 TO 1
6: 2 TO 3
7: 1 TO 3
8: 1 TO 2
9: 3 TO 2
10: 3 TO 1
11: 2 TO 1
12: 3 TO 2
13: 1 TO 3
14: 1 TO 2
15: 3 TO 2 </pre>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">call move(4,1,2,3)
print "Towers of Hanoi puzzle completed!"
end
Line 395 ⟶ 1,182:
call move(n-1, viaPeg, toPeg, fromPeg)
end if
end subroutine</langsyntaxhighlight>
 
{{out}}
Line 416 ⟶ 1,203:
Towers of Hanoi puzzle completed!
</pre>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Hanoi.bas"
110 CALL HANOI(4,1,3,2)
120 DEF HANOI(DISK,FRO,TO,WITH)
130 IF DISK>0 THEN
140 CALL HANOI(DISK-1,FRO,WITH,TO)
150 PRINT "Move disk";DISK;"from";FRO;"to";TO
160 CALL HANOI(DISK-1,WITH,TO,FRO)
170 END IF
180 END DEF</syntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 445 ⟶ 1,243:
call :move !x! %via% %to% %from%
)
exit /b 0</langsyntaxhighlight>
{{Out}}
<pre>Move top disk from pole START to pole HELPER.
Line 467 ⟶ 1,265:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM Disc$(13),Size%(3)
FOR disc% = 1 TO 13
Disc$(disc%) = STRING$(disc%," ")+STR$disc%+STRING$(disc%," ")
Line 502 ⟶ 1,300:
Size%(peg%) = Size%(peg%)-1
PRINTTAB(13+26*(peg%-1)-disc%,20-Size%(peg%))STRING$(2*disc%+1," ");
ENDPROC</langsyntaxhighlight>
 
=={{header|BefungeBCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let start() be move(4, 1, 2, 3)
and move(n, src, via, dest) be if n > 0 do
$( move(n-1, src, dest, via)
writef("Move disk from pole %N to pole %N*N", src, dest);
move(n-1, via, src, dest)
$)</syntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3</pre>
 
=={{header|Befunge}}==
This is loosely based on the [[Towers_of_Hanoi#Python|Python]] sample. The number of disks is specified by the first integer on the stack (the initial character <tt>4</tt> in the example below). If you want the program to prompt the user for that value, you can replace the <tt>4</tt> with a <tt>&</tt> (the read integer command).
 
<langsyntaxhighlight lang="befunge">48*2+1>#v_:!#@_0" ksid evoM">:#,_$:8/:.v
>8v8:<$#<+9-+*2%3\*3/3:,+55.+1%3:$_,#!>#:<
: >/!#^_:0\:8/1-8vv,_$8%:3/1+.>0" gep ot"^
^++3-%3\*2/3:%8\*<>:^:"from peg "0\*8-1<</langsyntaxhighlight>
 
{{out}}
Line 529 ⟶ 1,352:
Move disk 2 from peg 1 to peg 3
Move disk 1 from peg 2 to peg 3</pre>
 
=={{header|BQN}}==
'''Based on:''' [[APL]]
 
<syntaxhighlight lang="bqn">Move ← {
𝕩⊑⊸≤0 ? ⟨⟩;
𝕊 n‿from‿to‿via:
l ← 𝕊 ⟨n-1, from, via, to⟩
r ← 𝕊 ⟨n-1, via, to, from⟩
l∾(<from‿to)∾r
}
{"Move disk from pole "∾(•Fmt 𝕨)∾" to pole "∾•Fmt 𝕩}´˘>Move 4‿1‿2‿3</syntaxhighlight>
<syntaxhighlight lang="text">┌─
╵"Move disk from pole 1 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2"
┘</syntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( move
= n from to via
. !arg:(?n,?from,?to,?via)
Line 542 ⟶ 1,394:
)
& move$(4,1,2,3)
);</langsyntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 3
Line 562 ⟶ 1,414:
=={{header|Brainf***}}==
 
<langsyntaxhighlight lang="brainfuck">[
This implementation is recursive and uses
a stack, consisting of frames that are 8
Line 714 ⟶ 1,566:
>>[<<+>>-]<< step = next
<
]</langsyntaxhighlight>
 
=={{header|Bruijn}}==
{{trans|Python}}
<syntaxhighlight lang="bruijn">
:import std/Combinator .
:import std/Number .
:import std/String .
 
hanoi y [[[[=?2 empty go]]]]
go [(4 --3 2 0) ++ str ++ (4 --3 0 1)] ((+6) - 1 - 0)
str "Move " ++ disk ++ " from " ++ source ++ " to " ++ destination ++ "\n"
disk number→string 3
source number→string 2
destination number→string 1
</syntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void move(int n, int from, int via, int to)
Line 733 ⟶ 1,600:
move(4, 1,2,3);
return 0;
}</langsyntaxhighlight>
 
Animate it for fun:<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Line 794 ⟶ 1,661:
text(1, 0, 1, "\n");
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">public void move(int n, int from, int to, int via) {
if (n == 1) {
System.Console.WriteLine("Move disk from pole " + from + " to pole " + to);
Line 805 ⟶ 1,672:
move(n - 1, via, to, from);
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|g++}}
<langsyntaxhighlight lang="cpp">void move(int n, int from, int to, int via) {
if (n == 1) {
std::cout << "Move disk from pole " << from << " to pole " << to << std::endl;
Line 817 ⟶ 1,684:
move(n - 1, via, to, from);
}
}</langsyntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">100 cls
110 print "Three disks" : print
120 hanoi(3,1,2,3)
130 print chr$(10)"Four disks" chr$(10)
140 hanoi(4,1,2,3)
150 print : print "Towers of Hanoi puzzle completed!"
160 end
170 sub hanoi(n,desde,hasta,via)
180 if n > 0 then
190 hanoi(n-1,desde,via,hasta)
200 print "Move disk " n "from pole " desde "to pole " hasta
210 hanoi(n-1,via,hasta,desde)
220 endif
230 end sub</syntaxhighlight>
 
=={{header|Clojure}}==
===Side-Effecting Solution===
<lang lisp>(defn towers-of-hanoi [n from to via]
<syntaxhighlight lang="lisp">(defn towers-of-hanoi [n from to via]
(if (= n 1)
(when (pos? n)
(println (format "Move from %s to %s" from to))
(towers-of-hanoi (dec n) from via to)
(do
(printf "Move (towers-of-hanoifrom (dec%s to %s\n)" from via to)
(printlnrecur (formatdec "Moven) from %svia to %s" from to)))</syntaxhighlight>
===Lazy Solution===
(recur (dec n) via to from))))</lang>
<syntaxhighlight lang="lisp">(defn towers-of-hanoi [n from to via]
(when (pos? n)
(lazy-cat (towers-of-hanoi (dec n) from via to)
(cons [from '-> to]
(towers-of-hanoi (dec n) via to from)))))</syntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">move = proc (n, from, via, to: int)
po: stream := stream$primary_output()
if n > 0 then
move(n-1, from, to, via)
stream$putl(po, "Move disk from pole "
|| int$unparse(from)
|| " to pole "
|| int$unparse(to))
move(n-1, via, from, to)
end
end move
 
start_up = proc ()
move(4, 1, 2, 3)
end start_up</syntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3</pre>
 
=={{header|COBOL}}==
{{trans|C}}
{{works with|OpenCOBOL|2.0}}
<langsyntaxhighlight lang="cobol"> >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. towers-of-hanoi.
Line 858 ⟶ 1,781:
END-IF
.
END PROGRAM move-disk.</langsyntaxhighlight>
 
{{ Number of disks also }}
<langsyntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. towers-of-hanoi.
Line 891 ⟶ 1,814:
.
END PROGRAM move-disk.
</syntaxhighlight>
</lang>
 
=== ANSI-74 solution ===
 
Early versions of COBOL did not have recursion. There are no locally-scoped variables and the call of a procedure does not have to use a stack to save return state. Recursion would cause undefined results. It is therefore necessary to use an iterative algorithm. This solution is an adaptation of [http://hanoitower.mkolar.org/algo.html Kolar's Hanoi Tower algorithm no. 1].
 
{{works with|CIS COBOL|4.2}}{{works with|GnuCOBOL|3.0-rc1.0}}
 
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. ITERATIVE-TOWERS-OF-HANOI.
AUTHOR. SOREN ROUG.
DATE-WRITTEN. 2019-06-28.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. LINUX.
OBJECT-COMPUTER. KAYPRO4.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
WORKING-STORAGE SECTION.
77 NUM-DISKS PIC 9 VALUE 4.
77 N1 PIC 9 COMP.
77 N2 PIC 9 COMP.
77 FROM-POLE PIC 9 COMP.
77 TO-POLE PIC 9 COMP.
77 VIA-POLE PIC 9 COMP.
77 FP-TMP PIC 9 COMP.
77 TO-TMP PIC 9 COMP.
77 P-TMP PIC 9 COMP.
77 TMP-P PIC 9 COMP.
77 I PIC 9 COMP.
77 DIV PIC 9 COMP.
01 STACKNUMS.
05 NUMSET OCCURS 3 TIMES.
10 DNUM PIC 9 COMP.
01 GAMESET.
05 POLES OCCURS 3 TIMES.
10 STACK OCCURS 10 TIMES.
15 POLE PIC 9 USAGE COMP.
 
PROCEDURE DIVISION.
HANOI.
DISPLAY "TOWERS OF HANOI PUZZLE WITH ", NUM-DISKS, " DISKS.".
ADD NUM-DISKS, 1 GIVING N1.
ADD NUM-DISKS, 2 GIVING N2.
MOVE 1 TO DNUM (1).
MOVE N1 TO DNUM (2), DNUM (3).
MOVE N1 TO POLE (1, N1), POLE (2, N1), POLE (3, N1).
MOVE 1 TO POLE (1, N2).
MOVE 2 TO POLE (2, N2).
MOVE 3 TO POLE (3, N2).
MOVE 1 TO I.
PERFORM INIT-PUZZLE UNTIL I = N1.
MOVE 1 TO FROM-POLE.
DIVIDE 2 INTO NUM-DISKS GIVING DIV.
MULTIPLY 2 BY DIV.
IF DIV NOT = NUM-DISKS PERFORM INITODD ELSE PERFORM INITEVEN.
PERFORM MOVE-DISK UNTIL DNUM (3) NOT > 1.
DISPLAY "TOWERS OF HANOI PUZZLE COMPLETED!".
STOP RUN.
INIT-PUZZLE.
MOVE I TO POLE (1, I).
MOVE 0 TO POLE (2, I), POLE (3, I).
ADD 1 TO I.
INITEVEN.
MOVE 2 TO TO-POLE.
MOVE 3 TO VIA-POLE.
INITODD.
MOVE 3 TO TO-POLE.
MOVE 2 TO VIA-POLE.
MOVE-DISK.
MOVE DNUM (FROM-POLE) TO FP-TMP.
MOVE POLE (FROM-POLE, FP-TMP) TO I.
DISPLAY "MOVE DISK FROM ", POLE (FROM-POLE, N2),
" TO ", POLE (TO-POLE, N2).
ADD 1 TO DNUM (FROM-POLE).
MOVE VIA-POLE TO TMP-P.
SUBTRACT 1 FROM DNUM (TO-POLE).
MOVE DNUM (TO-POLE) TO TO-TMP.
MOVE I TO POLE (TO-POLE, TO-TMP).
DIVIDE 2 INTO I GIVING DIV.
MULTIPLY 2 BY DIV.
IF I NOT = DIV PERFORM MOVE-TO-VIA ELSE
PERFORM MOVE-FROM-VIA.
MOVE-TO-VIA.
MOVE TO-POLE TO VIA-POLE.
MOVE DNUM (FROM-POLE) TO FP-TMP.
MOVE DNUM (TMP-P) TO P-TMP.
IF POLE (FROM-POLE, FP-TMP) > POLE (TMP-P, P-TMP)
PERFORM MOVE-FROM-TO
ELSE MOVE TMP-P TO TO-POLE.
MOVE-FROM-TO.
MOVE FROM-POLE TO TO-POLE.
MOVE TMP-P TO FROM-POLE.
MOVE DNUM (FROM-POLE) TO FP-TMP.
MOVE DNUM (TMP-P) TO P-TMP.
MOVE-FROM-VIA.
MOVE FROM-POLE TO VIA-POLE.
MOVE TMP-P TO FROM-POLE.
</syntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">hanoi = (ndisks, start_peg=1, end_peg=3) ->
if ndisks
staging_peg = 1 + 2 + 3 - start_peg - end_peg
Line 901 ⟶ 1,923:
hanoi(ndisks-1, staging_peg, end_peg)
hanoi(4)</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun move (n from to via)
(cond ((= n 1)
(format t "Move from ~A to ~A.~%" from to))
Line 910 ⟶ 1,932:
(move (- n 1) from via to)
(format t "Move from ~A to ~A.~%" from to)
(move (- n 1) via to from))))</langsyntaxhighlight>
 
=={{header|D}}==
===Recursive Version===
<langsyntaxhighlight lang="d">import std.stdio;
 
void hanoi(in int n, in char from, in char to, in char via) {
Line 926 ⟶ 1,948:
void main() {
hanoi(3, 'L', 'M', 'R');
}</langsyntaxhighlight>
{{out}}
<pre>Move disk 1 from L to M
Line 937 ⟶ 1,959:
===Fast Iterative Version===
See: [http://hanoitower.mkolar.org/shortestTHalgo.html The shortest and "mysterious" TH algorithm]
<langsyntaxhighlight lang="d">// Code found and then improved by Glenn C. Rhoads,
// then some more by M. Kolar (2000).
void main(in string[] args) {
Line 979 ⟶ 2,001:
'\n'.putchar;
}
}</langsyntaxhighlight>
{{out}}
<pre>| 3 2 1
Line 1,015 ⟶ 2,037:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">main() {
moveit(from,to) {
print("move ${from} ---> ${to}");
Line 1,029 ⟶ 2,051:
 
hanoi(3,3,1,2);
}</langsyntaxhighlight>
 
The same as above, with optional static type annotations and styled according to http://www.dartlang.org/articles/style-guide/
<langsyntaxhighlight lang="dart">main() {
String say(String from, String to) => "$from ---> $to";
 
Line 1,044 ⟶ 2,066:
 
hanoi(3, 3, 1, 2);
}</langsyntaxhighlight>
 
{{out}}
Line 1,137 ⟶ 2,159:
lrx # run()
</pre>
 
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Towers_of_Hanoi#Pascal Pascal].
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc move(byte n, src, via, dest) void:
if n>0 then
move(n-1, src, dest, via);
writeln("Move disk from pole ",src," to pole ",dest);
move(n-1, via, src, dest)
fi
corp
 
proc nonrec main() void:
move(4, 1, 2, 3)
corp</syntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3</pre>
 
=={{header|Dyalect}}==
 
{{trans|Swift}}
 
<syntaxhighlight lang="dyalect">func hanoi(n, a, b, c) {
if n > 0 {
hanoi(n - 1, a, c, b)
print("Move disk from \(a) to \(c)")
hanoi(n - 1, b, a, c)
}
}
hanoi(4, "A", "B", "C")</syntaxhighlight>
 
{{out}}
 
<pre>Move disk from A to B
Move disk from A to C
Move disk from B to C
Move disk from A to B
Move disk from C to A
Move disk from C to B
Move disk from A to B
Move disk from A to C
Move disk from B to C
Move disk from B to A
Move disk from C to A
Move disk from B to C
Move disk from A to B
Move disk from A to C
Move disk from B to C</pre>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def move(out, n, fromPeg, toPeg, viaPeg) {
if (n.aboveZero()) {
move(out, n.previous(), fromPeg, viaPeg, toPeg)
Line 1,147 ⟶ 2,233:
}
 
move(stdout, 4, def left {}, def right {}, def middle {})</langsyntaxhighlight>
=={{header|Easyprog.online}}==
 
=={{header|EasyLang}}==
<lang easyprog.online>func hanoi n src dst aux . .
 
if n >= 1
<syntaxhighlight lang="text">
call hanoi n - 1 src aux dst
proc hanoi n src dst aux . .
print "Move " & src & " to " & dst
call hanoiif n ->= 1 aux dst src
hanoi n - 1 src aux dst
.
print "Move " & src & " to " & dst
hanoi n - 1 aux dst src
.
.
call hanoi 5 1 2 3</lang>
</syntaxhighlight>
 
=={{header|EDSAC order code}}==
The Wikipedia article on EDSAC says "recursive calls were forbidden", and this is true if the standard "Wheeler jump" is used. In the Wheeler jump, the caller (in effect) passes the return address to the subroutine, which uses that address to manufacture a "link order", i.e. a jump back to the caller. This link order is normally stored at a fixed location in the subroutine, so if the subroutine were to call itself then the original link order would be overwritten and lost. However, it is easy enough to make a subroutine save its link orders in a stack, so that it can be called recursively, as the Rosetta Code task requires.
 
The program has a maximum of 9 discs, so as to simplify the printout of the disc numbers. Discs are numbered 1, 2, 3, ... in increasing order of size. The program could be speeded up by shortening the messages, which at present take up most of the runtime.
<syntaxhighlight lang="edsac">
[Towers of Hanoi task for Rosetta Code.]
[EDSAC program, Initial Orders 2.]
 
T100K [load program at location 100 (arbitrary)]
GK
[Number of discs, in the address field]
[0] P3F [<--- edit here, value 1..9]
[Letters to represent the rods]
[1] LF [left]
[2] CF [centre]
[3] RF [right]
 
[Main routine. Enter with acc = 0]
[4] T1F [1F := 0]
[5] A5@ [initialize recursive subroutine]
G104@
A@ [number of discs]
T1F [pass to subroutines]
A1@ [source rod]
T4F [pass to subroutines]
A3@ [target rod]
T5F [pass to subroutines]
[13] A13@ [call subroutine to write header ]
G18@
[15] A15@ [call recursive subroutine to write moves ]
G104@
ZF [stop]
 
[Subroutine to write a header]
[Input: 1F = number of discs (in the address field)]
[4F = letter for starting rod]
[5F = letter for ending rod]
[Output: None. 1F, 4F, 5F must be preserved.]
[18] A3F [plant return link as usual]
T35@
A1F [number of discs]
L512F [shift 11 left to make output char]
T39@ [plant in message]
A4F [starting rod]
T53@ [plant in message]
A5F [ending rod]
T58@ [plant in message]
A36@ [O order for first char of message]
E30@ [skip next order (code for 'O' is positive)]
[29] A37@ [restore acc after test below]
[30] U31@ [plant order to write next character]
[31] OF [(planted) write next character]
A2F [inc address in previous order]
S37@ [finished yet?]
G29@ [if not, loop back]
[35] ZF [(planted) exit with acc = 0]
[36] O38@ [O order for start of message]
[37] O61@ [O order for exclusive end of message]
[38] #F
[39] PFK2048F!FDFIFSFCFSF!FFFRFOFMF!F
[53] PF!FTFOF!F
[58] PF@F&F
[61]
 
[Subroutine to write a move of one disc.]
[Input: 1F = disc number 1..9 (in the address field)]
[4F = letter for source rod]
[5F = letter for target rod]
[Output: None. 1F, 4F, 5F must be preserved.]
[Condensed to save space; very similar to previous subroutine.]
[61] A3FT78@A1FL512FT88@ A4FT96@A5FT101@A79@E73@
[72] A80@
[73] U74@
[74] OFA2FS80@G72@
[78] ZF [(planted) exit with acc = 0]
[79] O81@
[80] O104@
[81] K2048FMFOFVFEF!F#F
[88] PFK2048F!FFFRFOFMF!F
[96] PF!FTFOF!F
[101] PF@F&F
[104]
 
[Recursive subroutine to move discs 1..n, where 1 <= n <= 9.]
[Call with n = 0 to initialize.]
[Input: 1F = n (in the address field)]
[4F = letter for source rod]
[5F = letter for target rod]
[Output: None. 1F, 4F, 5F must be preserved.]
[104] A3F [plant link as usual ]
T167@
[The link will be saved in a stack if recursive calls are required.]
S1F [load -n]
G115@ [jump if n > 0]
[Here if n = 0. Initialize; no recursive calls.]
A169@ [initialize push order to start of stack]
T122@
A1@ [find total of the codes for the rod letters]
A2@
A3@
T168@ [store for future use]
E167@ [jump to link]
[Here with acc = -n in address field]
[115] A2F [add 1]
G120@ [jump if n > 1]
[Here if n = 1. Just write the move; no recursive calls.]
[117] A117@ [call write subroutine]
G61@
E167@ [jump to link]
[Here if n > 1. Recursive calls are required.]
[120] TF [clear acc]
A167@ [load link order]
[122] TF [(planted) push link order onto stack]
A122@ [inc address in previous order]
A2F
T122@
[First recursive call. Modify parameters 1F and 5F; 4F stays the same]
A1F [load n]
S2F [make n - 1]
T1F [pass as parameter]
A168@ [get 3rd rod, neither source nor target]
S4F
S5F
T5F
[133] A133@ [recursive call]
G104@
[Returned, restore parameters]
A1F
A2F
T1F
A168@
S4F
S5F
T5F
[Write move of largest disc]
[142] A142@
G61@
[Second recursive call. Modify parameters 1F and 4F; 5F stays the same]
[Condensed to save space; very similar to first recursice call.]
A1FS2FT1FA168@S4FS5FT4F
[151] A151@G104@A1FA2FT1FA168@S4FS5FT4F
[Pop return link off stack]
A122@ [dec address in push order]
S2F
U122@
A170@ [make A order with same address]
T165@ [plant in code]
[165] AF [(planted) pop return link from stack]
T167@ [plant in code]
[167] ZF [(planted) return to caller]
[Constants]
[168] PF [(planted) sum of letters for rods]
[169] T171@ [T order for start of stack]
[170] MF [add to T order to make A order, same address]
[Stack: placed at end of program, grows into free space.]
[171]
E4Z [define entry point]
PF [acc = 0 on entry]
[end]
</syntaxhighlight>
{{out}}
<pre>
3 DISCS FROM L TO R
MOVE 1 FROM L TO R
MOVE 2 FROM L TO C
MOVE 1 FROM R TO C
MOVE 3 FROM L TO R
MOVE 1 FROM C TO L
MOVE 2 FROM C TO R
MOVE 1 FROM L TO R
</pre>
 
=={{header|Eiffel}}==
<langsyntaxhighlight Eiffellang="eiffel">class
APPLICATION
 
Line 1,187 ⟶ 2,448:
end
end
end</langsyntaxhighlight>
 
=={{header|Ela}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="ela">open monad io
:::IO
 
Line 1,207 ⟶ 2,468:
hanoiM' (n - 1) a c b
putStrLn $ "Move " ++ show a ++ " to " ++ show b
hanoiM' (n - 1) c b a</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x :
<langsyntaxhighlight lang="elena">move = (n,from,to,via)
{
if (n == 1)
Line 1,222 ⟶ 2,484:
move(n-1,via,to,from)
}
};</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def hanoi(n) when 0<n and n<10, do: hanoi(n, 1, 2, 3)
Line 1,238 ⟶ 2,500:
end
 
RC.hanoi(3)</langsyntaxhighlight>
 
{{out}}
Line 1,253 ⟶ 2,515:
=={{header|Emacs Lisp}}==
{{Trans|Common Lisp}}
<syntaxhighlight lang="lisp">(defun move (n from to via)
<lang lisp>
(defun move (nif from(= ton via1)
(message "Move from %S to %S" from to)
(cond ((= n 1)
(printmove (format- "Moven 1) from %Svia to %S" from to)))
(message "Move from %S to %S" from to)
(t
(move (- n 1) via to from)))</syntaxhighlight>
(progn
 
(move (- n 1) from via to)
=={{header|EMal}}==
(print (format "Move from %S to %S" from to))
{{trans|C#}}
(move (- n 1) via to from)))))
</syntaxhighlight lang="emal">
fun move = void by int n, int from, int to, int via
if n == 1
writeLine("Move disk from pole " + from + " to pole " + to)
return
end
move(n - 1, from, via, to)
move(1, from, to, via)
move(n - 1, via, to, from)
end
move(3, 1, 2, 3)
</syntaxhighlight>
{{out}}
<pre>
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">move(1, F, T, _V) ->
io:format("Move from ~p to ~p~n", [F, T]);
move(N, F, T, V) ->
move(N-1, F, V, T),
move(1 , F, T, V),
move(N-1, V, T, F).</langsyntaxhighlight>
 
=={{header|ERRE}}==
<langsyntaxhighlight lang="erre">
!-----------------------------------------------------------
! HANOI.R : solve tower of Hanoi puzzle using a recursive
Line 1,329 ⟶ 2,612:
MOVE
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,344 ⟶ 2,627:
I move a disk from Left to Right
</pre>
 
=={{header|Excel}}==
===LAMBDA===
With the names HANOI and SHOWHANOI bound to the following lambdas in the Excel worksheet Name Manager:
 
(See [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ LAMBDA: The ultimate Excel worksheet function])
 
{{Works with| Office 365 Betas 2021}}
<syntaxhighlight lang="lisp">SHOWHANOI
=LAMBDA(n,
FILTERP(
LAMBDA(x, "" <> x)
)(
HANOI(n)("left")("right")("mid")
)
)
 
 
HANOI
=LAMBDA(n,
LAMBDA(l,
LAMBDA(r,
LAMBDA(m,
IF(0 = n,
"",
LET(
next, n - 1,
APPEND(
APPEND(
HANOI(next)(l)(m)(r)
)(
CONCAT(l, " -> ", r)
)
)(
HANOI(next)(m)(r)(l)
)
)
)
)
)
)
)</syntaxhighlight>
 
And assuming that these generic lambdas are also bound to the following names in Name Manager:
 
<syntaxhighlight lang="lisp">APPEND
=LAMBDA(xs,
LAMBDA(ys,
LET(
nx, ROWS(xs),
rowIndexes, SEQUENCE(nx + ROWS(ys)),
colIndexes, SEQUENCE(
1,
MAX(COLUMNS(xs), COLUMNS(ys))
),
IF(
rowIndexes <= nx,
INDEX(xs, rowIndexes, colIndexes),
INDEX(ys, rowIndexes - nx, colIndexes)
)
)
)
)
 
 
FILTERP
=LAMBDA(p,
LAMBDA(xs,
FILTER(xs, p(xs))
)
)</syntaxhighlight>
 
In the output below, the expression in B2 defines an array of strings which additionally populate the following cells.
 
{{Out}}
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="2" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=SHOWHANOI(A2)
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
| style="text-align:right; font-weight:bold" | Disks
| style="font-weight:bold" | Steps
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="text-align:right; font-weight:bold" | 3
| style="background-color:#cbcefb;" | left -> right
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
| style="text-align:right; font-weight:bold" |
| left -> mid
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 4
| style="text-align:right; font-weight:bold" |
| right -> mid
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 5
| style="text-align:right; font-weight:bold" |
| left -> right
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 6
| style="text-align:right; font-weight:bold" |
| mid -> left
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 7
| style="text-align:right; font-weight:bold" |
| mid -> right
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 8
| style="text-align:right; font-weight:bold" |
| left -> right
|}
 
=={{header|Ezhil}}==
<syntaxhighlight lang="python">
<lang Python>
# (C) 2013 Ezhil Language Project
# Tower of Hanoi – recursive solution
Line 1,374 ⟶ 2,773:
 
ஹோனாய்(4,”அ”,”ஆ”,0)
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">#light
let rec hanoi num start finish =
match num with
Line 1,388 ⟶ 2,787:
(hanoi 4 1 2) |> List.iter (fun pair -> match pair with
| a, b -> printf "Move disc from %A to %A\n" a b)
0</langsyntaxhighlight>
 
=={{header|FALSE}}==
<lang false>["Move disk from "$!\" to "$!\"
"]p: { to from }
[n;0>[n;1-n: @\ h;! @\ p;! \@ h;! \@ n;1+n:]?]h: { via to from }
4n:["right"]["middle"]["left"]h;!%%%</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel locals math ;
IN: rosettacode.hanoi
 
Line 1,407 ⟶ 2,800:
from to move
n 1 - other to from hanoi
] when ;</langsyntaxhighlight>
In the REPL:
<pre>( scratchpad ) 3 1 3 2 hanoi
Line 1,418 ⟶ 2,811:
1->3</pre>
 
=={{header|FōrmulæFALSE}}==
<syntaxhighlight lang="false">["Move disk from "$!\" to "$!\"
"]p: { to from }
[n;0>[n;1-n: @\ h;! @\ p;! \@ h;! \@ n;1+n:]?]h: { via to from }
4n:["right"]["middle"]["left"]h;!%%%</syntaxhighlight>
 
=={{header|Fermat}}==
In [http://wiki.formulae.org/Towers_of_Hanoi this] page you can see the solution of this task.
<syntaxhighlight lang="fermat">Func Hanoi( n, f, t, v ) =
if n = 0 then
!'';
else
Hanoi(n - 1, f, v, t);
!f;!' -> ';!t;!', ';
Hanoi(n - 1, v, t, f)
fi.</syntaxhighlight>
{{out}}<pre>1 -> 3, 1 -> 2, 3 -> 2, 1 -> 3, 2 -> 1, 2 -> 3, 1 -> 3, 1 -> 2, 3 -> 2, 3 -> 1, 2 -> 1, 3 -> 2, 1 -> 3, 1 -> 2, 3 -> 2,</pre>
 
=={{header|FOCAL}}==
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
<syntaxhighlight lang="focal">01.10 S N=4;S S=1;S V=2;S T=3
01.20 D 2
01.30 Q
 
02.02 S N(D)=N(D)-1;I (N(D)),2.2,2.04
02.04 S D=D+1
02.06 S N(D)=N(D-1);S S(D)=S(D-1)
02.08 S T(D)=V(D-1);S V(D)=T(D-1)
02.10 D 2
02.12 S D=D-1
02.14 D 3
02.16 S A=S(D);S S(D)=V(D);S V(D)=A
02.18 G 2.02
02.20 D 3
 
03.10 T %1,"MOVE DISK FROM POLE",S(D)
03.20 T " TO POLE",T(D),!</syntaxhighlight>
 
{{out}}
 
<pre>MOVE DISK FROM POLE= 1 TO POLE= 2
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
MOVE DISK FROM POLE= 1 TO POLE= 3
MOVE DISK FROM POLE= 2 TO POLE= 3
MOVE DISK FROM POLE= 1 TO POLE= 2
MOVE DISK FROM POLE= 3 TO POLE= 1
MOVE DISK FROM POLE= 3 TO POLE= 2
MOVE DISK FROM POLE= 1 TO POLE= 2
MOVE DISK FROM POLE= 1 TO POLE= 3
MOVE DISK FROM POLE= 2 TO POLE= 3
MOVE DISK FROM POLE= 2 TO POLE= 1
MOVE DISK FROM POLE= 3 TO POLE= 1
MOVE DISK FROM POLE= 2 TO POLE= 3
MOVE DISK FROM POLE= 1 TO POLE= 2
MOVE DISK FROM POLE= 1 TO POLE= 3
MOVE DISK FROM POLE= 2 TO POLE= 3</pre>
 
=={{header|Forth}}==
With locals:
<langsyntaxhighlight lang="forth">CREATE peg1 ," left "
CREATE peg2 ," middle "
CREATE peg3 ," right "
Line 1,440 ⟶ 2,879:
1 from to via RECURSE
n 1- via to from RECURSE
THEN ;</langsyntaxhighlight>
Without locals, executable pegs:
<langsyntaxhighlight lang="forth">: left ." left" ;
: right ." right" ;
: middle ." middle" ;
Line 1,455 ⟶ 2,894:
swap rot ;
: hanoi ( n -- )
1 max >R ['] right ['] middle ['] left R> move-disk drop drop drop ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">PROGRAM TOWER
CALL Move(4, 1, 2, 3)
Line 1,477 ⟶ 2,916:
END SUBROUTINE Move
 
END PROGRAM TOWER</langsyntaxhighlight>
 
{{ More informative version }}
<syntaxhighlight lang="fortran">
PROGRAM TOWER2
CALL Move(4, 1, 2, 3)
CONTAINS
RECURSIVE SUBROUTINE Move(ndisks, from, via, to)
INTEGER, INTENT (IN) :: ndisks, from, via, to
IF (ndisks > 1) THEN
CALL Move(ndisks-1, from, to, via)
WRITE(*, "(A,I1,A,I1,A,I1)") "Move disk ", ndisks, " from pole ", from, " to pole ", to
Call Move(ndisks-1,via,from,to)
ELSE
WRITE(*, "(A,I1,A,I1,A,I1)") "Move disk ", ndisks, " from pole ", from, " to pole ", to
END IF
END SUBROUTINE Move
END PROGRAM TOWER2 </syntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub move(n As Integer, from As Integer, to_ As Integer, via As Integer)
Line 1,496 ⟶ 2,957:
move 4, 1, 2, 3
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,528 ⟶ 2,989:
Move disk 1 from pole 3 to pole 2
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">
/** Set up the recursive call for n disks */
hanoi[n] := hanoi[n, 1, 3, 2]
 
/** The recursive call. */
hanoi[n, source, target, aux] :=
{
if n > 0
{
hanoi[n-1, source, aux, target]
println["Move from $source to $target"]
hanoi[n-1, aux, target, source]
}
}
 
hanoi[7]
</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1, @"Towers of Hanoi", ( 0, 0, 300, 300 )
<lang futurebasic>
 
include "ConsoleWindow"
void local fn Move( n as long, fromPeg as long, toPeg as long, viaPeg as long )
if n > 0
void local fn move( n as long, fromPeg as long, toPeg as long, viaPeg as long )
fn Move( n-1, fromPeg, viaPeg, toPeg )
if n > 0
fn move(print n-1,"Move disk from "; fromPeg,; viaPeg," toPegto )"; toPeg
print "fn Move( diskn-1, fromviaPeg, ";toPeg, fromPeg; " to "; toPeg)
end if
fn move( n-1, viaPeg, toPeg, fromPeg )
end if
end fn
 
fn moveMove( 4, 1, 2, 3 )
print
print "Towers of Hanoi puzzle solved."
end
 
HandleEvents</syntaxhighlight>
</lang>
 
Output:
Line 1,568 ⟶ 3,046:
Towers of Hanoi puzzle solved.
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Tower_of_Hanoi}}
 
'''Solution'''
 
[[File:Fōrmulæ - Tower of Hanoi 01.png]]
 
'''Test case'''
 
[[File:Fōrmulæ - Tower of Hanoi 02.png]]
 
[[File:Fōrmulæ - Tower of Hanoi 03.png]]
 
=={{header|Gambas}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
Print "Three disks\n"
move_(3, 1, 2, 3)
Print
Print "Four disks\n"
move_(4, 1, 2, 3)
End
 
Public Sub move_(n As Integer, from As Integer, to As Integer, via As Integer)
 
If n > 0 Then
move_(n - 1, from, via, to)
Print "Move disk "; n; " from pole "; from; " to pole "; to
move_(n - 1, via, to, from)
End If
 
End Sub </syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">Hanoi := function(n)
local move;
move := function(n, a, b, c) # from, through, to
Line 1,599 ⟶ 3,115:
# B -> A
# B -> C
# A -> C</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,643 ⟶ 3,159:
func (t *towers) move1(from, to int) {
fmt.Println("move disk from rod", from, "to rod", to)
}</langsyntaxhighlight>
 
In other words:
 
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,661 ⟶ 3,177:
move(n-1, b, a, c)
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Unlike most solutions here this solution manipulates more-or-less actual stacks of more-or-less actual rings.
<langsyntaxhighlight lang="groovy">def tail = { list, n -> def m = list.size(); list.subList([m - n, 0].max(),m) }
 
final STACK = [A:[],B:[],C:[]].asImmutable()
Line 1,681 ⟶ 3,197:
moveRing(from, to)
moveStack(tail(using, n-1), to, from)
}</langsyntaxhighlight>
Test program:
<langsyntaxhighlight lang="groovy">enum Ring {
S('°'), M('o'), L('O'), XL('( )');
private sym
Line 1,696 ⟶ 3,212:
report()
check(STACK.A)
moveStack(STACK.A, STACK.C)</langsyntaxhighlight>
 
{{out}}
Line 1,767 ⟶ 3,283:
(i.e., print out movements as side effects during program execution).
Haskell favors a purely functional approach, where you would for example return a (lazy) list of movements from a to b via c:
<langsyntaxhighlight lang="haskell">hanoi :: Integer -> a -> a -> a -> [(a, a)]
hanoi 0 _ _ _ = []
hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a</langsyntaxhighlight>
 
You can also do the above with one tail-recursion call:
<langsyntaxhighlight lang="haskell">hanoi :: Integer -> a -> a -> a -> [(a, a)]
 
hanoi n a b c = hanoiToList n a b c []
where
hanoiToList 0 _ _ _ l = l
hanoiToList n a b c l = hanoiToList (n-1) a c b ((a, b) : hanoiToList (n-1) c b a l)</langsyntaxhighlight>
 
One can use this function to produce output, just like the other programs:
<langsyntaxhighlight lang="haskell">hanoiIO n = mapM_ f $ hanoi n 1 2 3 where
f (x,y) = putStrLn $ "Move " ++ show x ++ " to " ++ show y</langsyntaxhighlight>
or, instead, one can of course also program imperatively, using the IO monad directly:
<langsyntaxhighlight lang="haskell">hanoiM :: Integer -> IO ()
hanoiM n = hanoiM' n 1 2 3 where
hanoiM' 0 _ _ _ = return ()
Line 1,789 ⟶ 3,305:
hanoiM' (n-1) a c b
putStrLn $ "Move " ++ show a ++ " to " ++ show b
hanoiM' (n-1) c b a</langsyntaxhighlight>
 
or, defining it as a monoid, and adding some output:
<syntaxhighlight lang="haskell">-------------------------- HANOI -------------------------
<lang haskell>import Data.Monoid ((<>), mempty)
import Data.List (intercalate, transpose)
 
hanoi :: Int -> t -> t -> t -> [[t]]
Int ->
String ->
String ->
String ->
[(String, String)]
hanoi 0 _ _ _ = mempty
hanoi n l r m = hanoi (n - 1) l m r <> [[l, r]] <> hanoi (n - 1) m r l
hanoi (n - 1) l m r
<> [(l, r)]
<> hanoi (n - 1) m r l
 
--------------------------- TEST -------------------------
main :: IO ()
main = putStrLn $ showHanoi 5
 
------------------------- DISPLAY ------------------------
showHanoi :: Int -> String
showHanoi n =
unlines $
fmap
intercalate " -> " <$>
( \(from, to) ->
transpose
concat [justifyRight 5 ' ' from, " -> ", to]
((justifyLeft 6 ' ' <$>) <$> transpose (hanoi n "left" "right" "mid"))
)
(hanoi n "left" "right" "mid")
 
justifyLeftjustifyRight :: Int -> Char -> String -> String
justifyLeftjustifyRight n c s = take(drop n. (slength) <*> (replicate n c <>)</syntaxhighlight>
 
-- TEST -------------------------------------------------------------
main :: IO ()
main = putStrLn $ showHanoi 5</lang>
{{Out}}
<pre> left -> right
left -> mid
right -> mid
left -> right
mid mid -> left
mid mid -> right
left -> right
left -> mid
right -> mid
right -> left
mid mid -> left
right -> mid
left -> right
left -> mid
right -> mid
left -> right
mid mid -> left
mid mid -> right
left -> right
mid mid -> left
right -> mid
right -> left
mid mid -> left
mid mid -> right
left -> right
left -> mid
right -> mid
left -> right
mid mid -> left
mid mid -> right
left -> right</pre>
 
=={{header|HolyC}}==
{{trans|C}}
<langsyntaxhighlight lang="holyc">U0 Move(U8 n, U8 from, U8 to, U8 via) {
if (n > 0) {
Move(n - 1, from, via, to);
Line 1,855 ⟶ 3,381:
}
 
Move(4, 1, 2, 3);</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The following is based on a solution in the Unicon book.
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
hanoi(arglist[1]) | stop("Usage: hanoi n\n\rWhere n is the number of disks to move.")
end
Line 1,881 ⟶ 3,407:
}
return
end</langsyntaxhighlight>
 
=={{header|Imp77}}==
<syntaxhighlight lang="Imp77">
%begin
%routine do hanoi(%integer n, f, t, u)
do hanoi(n - 1, f, u, t) %if n >= 2
print string("Move disk from ".itos(f,0)." to ".itos(t,0).to string(nl))
do hanoi(n - 1, u, t, f) %if n >= 2
%end
do hanoi(4, 1, 2, 3)
print string("Towers of Hanoi puzzle completed!".to string(nl))
%end %of %program
</syntaxhighlight>
{{out}}
<pre>
Move disk from 1 to 3
Move disk from 1 to 2
Move disk from 3 to 2
Move disk from 1 to 3
Move disk from 2 to 1
Move disk from 2 to 3
Move disk from 1 to 3
Move disk from 1 to 2
Move disk from 3 to 2
Move disk from 3 to 1
Move disk from 2 to 1
Move disk from 3 to 2
Move disk from 1 to 3
Move disk from 1 to 2
Move disk from 3 to 2
Towers of Hanoi puzzle completed!
</pre>
 
=={{header|Inform 7}}==
<langsyntaxhighlight lang="inform7">Hanoi is a room.
 
A post is a kind of supporter. A post is always fixed in place.
Line 1,908 ⟶ 3,466:
if a topmost disk (called TD) is enclosed by TP, now D is on TD;
otherwise now D is on TP;
move N - 1 disks from VP to TP via FP.</langsyntaxhighlight>
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">hanoi := method(n, from, to, via,
if (n == 1) then (
writeln("Move from ", from, " to ", to)
Line 1,919 ⟶ 3,477:
hanoi(n - 1, via , to , from)
)
)</langsyntaxhighlight>
 
=={{header|Ioke}}==
<langsyntaxhighlight lang="ioke"> = method(n, f, u, t,
if(n < 2,
"#{f} --> #{t}" println,
Line 1,934 ⟶ 3,492:
hanoi = method(n,
H(n, 1, 2, 3)
)</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<lang IS-BASIC>100 PROGRAM "Hanoi.bas"
110 CALL HANOI(4,1,3,2)
120 DEF HANOI(DISK,FRO,TO,WITH)
130 IF DISK>0 THEN
140 CALL HANOI(DISK-1,FRO,WITH,TO)
150 PRINT "Move disk";DISK;"from";FRO;"to";TO
160 CALL HANOI(DISK-1,WITH,TO,FRO)
170 END IF
180 END DEF</lang>
 
=={{header|J}}==
'''Solutions'''
<langsyntaxhighlight lang="j">H =: i.@,&2 ` (({&0 2 1,0 2,{&1 0 2)@$:@<:) @. * NB. tacit using anonymous recursion</langsyntaxhighlight>
{{out|Example use}}
<langsyntaxhighlight lang="j"> H 3
0 2
0 1
Line 1,958 ⟶ 3,505:
1 2
1 0
2 0</langsyntaxhighlight>
The result is a 2-column table; a row <tt>i,j</tt> is interpreted as: move a disk (the top disk) from peg <tt>i</tt> to peg<tt> j</tt> .
Or, using explicit rather than implicit code:
<langsyntaxhighlight lang="j">H1=: monad define NB. explicit equivalent of H
if. y do.
({&0 2 1 , 0 2 , {&1 0 2) H1 y-1
Line 1,967 ⟶ 3,514:
i.0 2
end.
)</langsyntaxhighlight>
The usage here is the same:
<pre> H1 2
Line 1,975 ⟶ 3,522:
;Alternative solution
If a textual display is desired, similar to some of the other solutions here (counting from 1 instead of 0, tracking which disk is on the top of the stack, and of course formatting the result for a human reader instead of providing a numeric result):
<langsyntaxhighlight Jlang="j">hanoi=: monad define
moves=. H y
disks=. $~` ((],[,]) $:@<:) @.* y
('move disk ';' from peg ';' to peg ');@,."1 ":&.>disks,.1+moves
)</langsyntaxhighlight>
{{out|Demonstration}}
<langsyntaxhighlight Jlang="j"> hanoi 3
move disk 1 from peg 1 to peg 3
move disk 2 from peg 1 to peg 2
Line 1,988 ⟶ 3,535:
move disk 1 from peg 2 to peg 1
move disk 2 from peg 2 to peg 3
move disk 1 from peg 1 to peg 3</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public void move(int n, int from, int to, int via) {
if (n == 1) {
System.out.println("Move disk from pole " + from + " to pole " + to);
Line 1,999 ⟶ 3,546:
move(n - 1, via, to, from);
}
}</langsyntaxhighlight>
 
Where n is the number of disks to move and from, to, and via are the poles.
 
{{out|Example use}}
<syntaxhighlight lang="java">move(3, 1, 2, 3);</syntaxhighlight>
 
{{Out}}
<syntaxhighlight lang="java">Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2</syntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">function move(n, a, b, c) {
if (n > 0) {
move(n-1, a, c, b);
Line 2,010 ⟶ 3,571:
}
}
move(4, "A", "B", "C");</langsyntaxhighlight>
 
 
Or, as a functional expression, rather than a statement with side effects:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// hanoi :: Int -> String -> String -> String -> [[String, String]]
Line 2,030 ⟶ 3,591:
return d[0] + ' -> ' + d[1];
});
})();</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">["left -> right", "left -> mid",
"right -> mid", "left -> right",
"mid -> left", "mid -> right",
"left -> right"]</langsyntaxhighlight>
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// ----------------- TOWERS OF HANOI -----------------
<lang JavaScript>(() => {
'use strict';
 
// hanoi :: Int -> String -> String -> String -> [[String, String]]
const// hanoiString =-> (n[[String, a, b, c) =>String]]
const hanoi = n ? hanoi(n - 1, a, c, b)=>
.concat([a, b, c) => {
[a,const b]go = hanoi(n - 1);
])
.concat(hanoi(n - 1, c, b, a)) : [];
 
// show :: a -> String return n
const show = x => JSON.stringify(x, null, 2); ? [
...go(a, c, b),
[a, b],
...go(c, b, a)
]
: [];
};
 
return show(
hanoi(3, 'left', 'right', 'mid')
.map(d => d[0] + ' -> ' + d[1])
);
})();</lang>
 
// ---------------------- TEST -----------------------
return hanoi(3)("left", "right", "mid")
.map(d => `${d[0]} -> ${d[1]}`)
.join("\n");
})();</syntaxhighlight>
{{Out}}
<pre>[left -> right
"left -> right",mid
"leftright -> mid",
"rightleft -> mid",right
"leftmid -> right",left
"mid -> left",right
"midleft -> right",</pre>
"left -> right"
]</pre>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE hanoi == [[rolldown] infra] dip
From [http://www.latrobe.edu.au/phimvt/joy/jp-nestrec.html here]
[[[null] [pop pop] ]
<lang joy>DEFINE hanoi == [[rolldown] infra] dip
[[dup2 [[rotate] infra] dip pred]
[ [ [null] [pop pop] ]
[[dup rest put] dip
[ [dup2 [[rotate] infra] dip pred]
[ [dupswap] rest putinfra] dip pred]
[]]]
[[swap] infra] dip pred ]
condnestrec.</syntaxhighlight>
[] ] ]
condnestrec.</lang>
Using it (5 is the number of disks.)
<langsyntaxhighlight lang="joy">[source destination temp] 5 hanoi.</langsyntaxhighlight>
 
=={{header|jq}}==
Line 2,097 ⟶ 3,660:
 
The truth of (b) follows from the fact that the algorithm emits an instruction of what to do when moving a single disk.
<langsyntaxhighlight lang="jq"># n is the number of disks to move from From to To
def move(n; From; To; Via):
if n > 0 then
Line 2,107 ⟶ 3,670:
move(n-1; Via; To; From)
else empty
end;</langsyntaxhighlight>
'''Example''':
move(5; "A"; "B"; "C")
 
=={{header|Jsish}}==
From Javascript ES5 entry.
<syntaxhighlight lang="javascript">/* Towers of Hanoi, in Jsish */
 
function move(n, a, b, c) {
if (n > 0) {
move(n-1, a, c, b);
puts("Move disk from " + a + " to " + c);
move(n-1, b, a, c);
}
}
 
if (Interp.conf('unitTest')) move(4, "A", "B", "C");
 
/*
=!EXPECTSTART!=
Move disk from A to B
Move disk from A to C
Move disk from B to C
Move disk from A to B
Move disk from C to A
Move disk from C to B
Move disk from A to B
Move disk from A to C
Move disk from B to C
Move disk from B to A
Move disk from C to A
Move disk from B to C
Move disk from A to B
Move disk from A to C
Move disk from B to C
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish -u towersOfHanoi.jsi
[PASS] towersOfHanoi.jsi</pre>
 
=={{header|Julia}}==
{{trans|R}}
<langsyntaxhighlight lang="julia">
function solve(n::Integer, from::Integer, to::Integer, via::Integer)
if n == 1
Line 2,125 ⟶ 3,726:
 
solve(4, 1, 2, 3)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,147 ⟶ 3,748:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> h:{[n;a;b;c]if[n>0;_f[n-1;a;c;b];`0:,//$($n,":",$a,"->",$b,"\n");_f[n-1;c;b;a]]}
h[4;1;2;3]
1:1->3
Line 2,163 ⟶ 3,764:
1:1->3
2:1->2
1:3->2</langsyntaxhighlight>
The disk to move in the i'th step is the same as the position of the leftmost 1 in the binary representation of 1..2^n.
<langsyntaxhighlight Klang="k"> s:();{[n;a;b;c]if[n>0;_f[n-1;a;c;b];s,:n;_f[n-1;c;b;a]]}[4;1;2;3];s
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
 
1_{*1+&|x}'a:(2_vs!_2^4)
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1</langsyntaxhighlight>
 
=={{header|Klingphix}}==
{{trans|MiniScript}}
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy
 
:moveDisc %B !B %C !C %A !A %n !n { n A C B }
$n [
$n 1 - $A $B $C moveDisc
( "Move disc " $n " from pole " $A " to pole " $C ) lprint nl
$n 1 - $B $C $A moveDisc
] if
;
{ Move disc 3 from pole 1 to pole 3, with pole 2 as spare }
3 1 3 2 moveDisc
 
" " input</syntaxhighlight>
{{out}}
<pre>Move disc 1 from pole 1 to pole 3
Move disc 2 from pole 1 to pole 2
Move disc 1 from pole 3 to pole 2
Move disc 3 from pole 1 to pole 3
Move disc 1 from pole 2 to pole 1
Move disc 2 from pole 2 to pole 3
Move disc 1 from pole 1 to pole 3</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
class Hanoi(disks: Int) {
Line 2,196 ⟶ 3,822:
Hanoi(3)
Hanoi(4)
}</langsyntaxhighlight>
 
{{out}}
Line 2,233 ⟶ 3,859:
</pre>
 
=={{header|lambdatalkLambdatalk}}==
 
(Following NewLisp, PicoLisp, Racket, Scheme)
<langsyntaxhighlight lang="scheme">
PSEUDO-CODE:
{def move
 
{lambda {:n :from :to :via}
hanoi disks from A to B via C
{if {<= :n 0}
if thenno >disks
then stop
else {move {- :n 1} :from :via :to}
else hanoi upper move disk :ndisks from :fromA to :toC via {br}B
{move {- :nlower 1}disk :via :from A to :from}B }}}
hanoi upper disks from C to B via A
-> move
 
{move 4 A B C}
CODE:
> move disk 1 from A to C
 
> move disk 2 from A to B
{def hanoi
> move disk 1 from C to B
{lambda {:disks :a :b :c}
> move disk 3 from A to C
{if {A.empty? :disks}
> move disk 1 from B to A
then
> move disk 2 from B to C
else {hanoi {A.rest :disks} :a :c :b}
> move disk 1 from A to C
{div > move disk{A.first 4:disks} from A:a to B:b}
{hanoi {A.rest :disks} :c :b :a} }}}
> move disk 1 from C to B
-> hanoi
> move disk 2 from C to A
 
> move disk 1 from B to A
{hanoi {A.new ==== === == =} A B C}
> move disk 3 from C to B
->
> move disk 1 from A to C
> move disk 2= from A to BC
> move disk 1== from CA to B
> move = from C to B
</lang>
> move === from A to C
> move = from B to A
> move == from B to C
> move = from A to C
> move ==== from A to B
> move = from C to B
> move == from C to A
> move = from B to A
> move === from C to B
> move = from A to C
> move == from A to B
> move = from C to B
</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
 
define towermove(
Line 2,276 ⟶ 3,915:
}
 
towermove((integer($argv -> second || 3)), "A", "B", "C")</langsyntaxhighlight>
Called from command line:
<syntaxhighlight lang Lasso="lasso">./towers</langsyntaxhighlight>
{{out}}
<pre>Move disk from A to C
Line 2,288 ⟶ 3,927:
Move disk from A to C</pre>
Called from command line:
<syntaxhighlight lang Lasso="lasso">./towers 4</langsyntaxhighlight>
{{out}}
<pre>Move disk from A to B
Line 2,308 ⟶ 3,947:
=={{header|Liberty BASIC}}==
This looks much better with a GUI interface.
<langsyntaxhighlight lang="lb"> source$ ="A"
via$ ="B"
target$ ="C"
Line 2,326 ⟶ 3,965:
end sub
 
end</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on hanoi (n, a, b, c)
if n > 0 then
hanoi(n-1, a, c, b)
Line 2,335 ⟶ 3,974:
hanoi(n-1, b, a, c)
end if
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">hanoi(3, "A", "B", "C")
-- "Move disk from A to C"
-- "Move disk from A to B"
Line 2,343 ⟶ 3,982:
-- "Move disk from B to A"
-- "Move disk from B to C"
-- "Move disk from A to C"</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to move :n :from :to :via
if :n = 0 [stop]
move :n-1 :from :via :to
Line 2,352 ⟶ 3,991:
move :n-1 :via :to :from
end
move 4 "left "middle "right</langsyntaxhighlight>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">:- object(hanoi).
 
:- public(run/1).
Line 2,383 ⟶ 4,022:
nl.
 
:- end_object.</langsyntaxhighlight>
 
 
=={{header|LOLCODE}}==
<syntaxhighlight lang="lolcode">HAI 1.2
<lang LOLCODE>
HAI
HOW IZ I HANOI YR N AN YR SRC AN YR DST AN YR VIA
 
HOW DUZ I HANOI YR N AN YR SRC AN YR DST AN YR VIA
BTW VISIBLE SMOOSH "HANOI N=" N " SRC=" SRC " DST=" DST " VIA=" VIA MKAY
BOTH SAEM N AN 0, O RLY?
Line 2,398 ⟶ 4,035:
NO WAI
I HAS A LOWER ITZ DIFF OF N AN 1
I IZ HANOI DSTYR VIALOWER AN YR SRC LOWERAN YR VIA AN YR DST MKAY
VISIBLE SMOOSH "Move disc " N " from " SRC ..." to " DST MKAY
"I toIZ "HANOI YR LOWER AN YR VIA AN YR DST AN YR SRC MKAY
HANOI SRC DST VIA LOWER
OIC
IF U SAY SO
 
I IZ HANOI 2YR 34 AN YR 1 4AN BTWYR requires2 AN YR 3 reversed arguments?MKAY
 
KTHXBYE
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function move(n, src, dst, via)
if n > 0 then
move(n - 1, src, via, dst)
Line 2,419 ⟶ 4,055:
end
 
move(4, 1, 2, 3)</langsyntaxhighlight>
 
{{More informative version }}
<syntaxhighlight lang="lua">
 
function move(n, src, via, dst)
if n > 0 then
move(n - 1, src, dst, via)
print('Disk ',n,' from ' ,src, 'to', dst)
move(n - 1, via, src, dst)
end
end
move(4, 1, 2, 3)
 
</syntaxhighlight>
 
===Hanoi Iterative===
<syntaxhighlight lang="lua">
#!/usr/bin/env luajit
local function printf(fmt, ...) io.write(string.format(fmt, ...)) end
local runs=0
local function move(tower, from, to)
if #tower[from]==0
or (#tower[to]>0
and tower[from][#tower[from]]>tower[to][#tower[to]]) then
to,from=from,to
end
if #tower[from]>0 then
tower[to][#tower[to]+1]=tower[from][#tower[from]]
tower[from][#tower[from]]=nil
 
io.write(tower[to][#tower[to]],":",from, "→", to, " ")
end
end
 
local function hanoi(n)
local src,dst,via={},{},{}
local tower={src,dst,via}
for i=1,n do src[i]=n-i+1 end
local one,nxt,lst
if n%2==1 then -- odd
one,nxt,lst=1,2,3
else
one,nxt,lst=1,3,2
end
--repeat
::loop::
move(tower, one, nxt)
if #dst==n then return end
move(tower, one, lst)
one,nxt,lst=nxt,lst,one
goto loop
--until false
end
 
local num=arg[1] and tonumber(arg[1]) or 4
 
hanoi(num)
</syntaxhighlight>
{{out}}
<pre>
> ./hanoi_iter.lua 5
1:1→2 2:1→3 1:2→3 3:1→2 1:3→1 2:3→2 1:1→2 4:1→3 1:2→3 2:2→1 1:3→1 3:2→3 1:1→2 2:1→3 1:2→3 5:1→2 1:3→1 2:3→2 1:1→2 3:3→1 1:2→3 2:2→1 1:3→1 4:3→2 1:1→2 2:1→3 1:2→3 3:1→2 1:3→1 2:3→2 1:1→2
</pre>
 
===Hanoi Bitwise Fast===
<syntaxhighlight lang="lua">
#!/usr/bin/env luajit
-- binary solution
local bit=require"bit"
local band,bor=bit.band,bit.bor
local function hanoi(n)
local even=(n-1)%2
for m=1,2^n-1 do
io.write(m,":",band(m,m-1)%3+1, "→", (bor(m,m-1)+1)%3+1, " ")
end
end
 
local num=arg[1] and tonumber(arg[1]) or 4
 
hanoi(num)
</syntaxhighlight>
{{out}}
<pre>
> ./hanoi_bit.lua 4
1:1→3 2:1→2 3:3→2 4:1→3 5:2→1 6:2→3 7:1→3 8:1→2 9:3→2 10:3→1 11:2→1 12:3→2 13:1→3 14:1→2 15:3→2
> time ./hanoi_bit.lua 30 >/dev/null ; on AMD FX-8350 @ 4 GHz
./hanoi_bit.lua 30 > /dev/null 297,40s user 1,39s system 99% cpu 4:59,01 total
</pre>
 
=={{header|M2000 Interpreter}}==
{{trans|FreeBasic}}
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Hanoi {
Rem HANOI TOWERS
Line 2,440 ⟶ 4,167:
}
Hanoi
</syntaxhighlight>
</lang>
{{out}}
same as in FreeBasic
 
=={{header|MACRO-11}}==
<syntaxhighlight lang="macro11"> .TITLE HANOI
.MCALL .PRINT,.EXIT
HANOI:: MOV #4,R2
MOV #61,R3
MOV #62,R4
MOV #63,R5
JSR PC,MOVE
.EXIT
MOVE: DEC R2
BLT 1$
MOV R2,-(SP)
MOV R3,-(SP)
MOV R4,-(SP)
MOV R5,-(SP)
MOV R5,R0
MOV R4,R5
MOV R0,R4
JSR PC,MOVE
MOV (SP)+,R5
MOV (SP)+,R4
MOV (SP)+,R3
MOV (SP)+,R2
MOVB R3,3$
MOVB R4,4$
.PRINT #2$
MOV R3,R0
MOV R4,R3
MOV R5,R4
MOV R0,R5
BR MOVE
1$: RTS PC
2$: .ASCII /MOVE DISK FROM PEG /
3$: .ASCII /* TO PEG /
4$: .ASCIZ /*/
.EVEN
.END HANOI</syntaxhighlight>
{{out}}
<pre>MOVE DISK FROM PEG 1 TO PEG 3
MOVE DISK FROM PEG 1 TO PEG 2
MOVE DISK FROM PEG 2 TO PEG 3
MOVE DISK FROM PEG 1 TO PEG 3
MOVE DISK FROM PEG 3 TO PEG 1
MOVE DISK FROM PEG 3 TO PEG 2
MOVE DISK FROM PEG 2 TO PEG 1
MOVE DISK FROM PEG 1 TO PEG 2
MOVE DISK FROM PEG 2 TO PEG 3
MOVE DISK FROM PEG 2 TO PEG 1
MOVE DISK FROM PEG 1 TO PEG 3
MOVE DISK FROM PEG 2 TO PEG 3
MOVE DISK FROM PEG 3 TO PEG 2
MOVE DISK FROM PEG 3 TO PEG 1
MOVE DISK FROM PEG 1 TO PEG 2</pre>
 
=={{header|MAD}}==
 
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
DIMENSION LIST(100)
SET LIST TO LIST
VECTOR VALUES MOVFMT =
0 $20HMOVE DISK FROM POLE ,I1,S1,8HTO POLE ,I1*$
INTERNAL FUNCTION(DUMMY)
ENTRY TO MOVE.
LOOP NUM = NUM - 1
WHENEVER NUM.E.0
PRINT FORMAT MOVFMT,FROM,DEST
OTHERWISE
SAVE RETURN
SAVE DATA NUM,FROM,VIA,DEST
TEMP=DEST
DEST=VIA
VIA=TEMP
MOVE.(0)
RESTORE DATA NUM,FROM,VIA,DEST
RESTORE RETURN
PRINT FORMAT MOVFMT,FROM,DEST
TEMP=FROM
FROM=VIA
VIA=TEMP
TRANSFER TO LOOP
END OF CONDITIONAL
FUNCTION RETURN
END OF FUNCTION
NUM = 4
FROM = 1
VIA = 2
DEST = 3
MOVE.(0)
END OF PROGRAM
</syntaxhighlight>
 
{{out}}
 
<pre>MOVE DISK FROM POLE 1 TO POLE 2
MOVE DISK FROM POLE 1 TO POLE 3
MOVE DISK FROM POLE 2 TO POLE 3
MOVE DISK FROM POLE 1 TO POLE 2
MOVE DISK FROM POLE 3 TO POLE 1
MOVE DISK FROM POLE 3 TO POLE 2
MOVE DISK FROM POLE 1 TO POLE 2
MOVE DISK FROM POLE 1 TO POLE 3
MOVE DISK FROM POLE 2 TO POLE 3
MOVE DISK FROM POLE 2 TO POLE 1
MOVE DISK FROM POLE 3 TO POLE 1
MOVE DISK FROM POLE 2 TO POLE 3
MOVE DISK FROM POLE 1 TO POLE 2
MOVE DISK FROM POLE 1 TO POLE 3
MOVE DISK FROM POLE 2 TO POLE 3</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
Hanoi := proc(n::posint,a,b,c)
if n = 1 then
Line 2,458 ⟶ 4,298:
printf("Moving 2 disks from tower A to tower C using tower B.\n");
Hanoi(2,A,B,C);
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,470 ⟶ 4,310:
Move disk from tower B to tower C.
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">Hanoi[0, from_, to_, via_] := Null
Hanoi[n_Integer, from_, to_, via_] := (Hanoi[n-1, from, via, to];Print["Move disk from pole ", from, " to ", to, "."];Hanoi[n-1, via, to, from])</syntaxhighlight>
(Hanoi[n-1, from, via, to];
Print["Move disk from pole ", from, " to ", to, "."];
Hanoi[n-1, via, from, to])</lang>
 
=={{header|MATLAB}}==
This is a direct translation from the Python example given in the Wikipedia entry for the Tower of Hanoi puzzle.
<langsyntaxhighlight MATLABlang="matlab">function towerOfHanoi(n,A,C,B)
if (n~=0)
towerOfHanoi(n-1,A,B,C);
Line 2,485 ⟶ 4,322:
towerOfHanoi(n-1,B,C,A);
end
end</langsyntaxhighlight>
{{out|Sample output}}
<pre>towerOfHanoi(3,1,3,2)
Line 2,495 ⟶ 4,332:
Move plate 2 from tower 2 to tower 3
Move plate 1 from tower 1 to tower 3</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">moveDisc = function(n, A, C, B)
if n == 0 then return
moveDisc n-1, A, B, C
print "Move disc " + n + " from pole " + A + " to pole " + C
moveDisc n-1, B, C, A
end function
 
// Move disc 3 from pole 1 to pole 3, with pole 2 as spare
moveDisc 3, 1, 3, 2</syntaxhighlight>
{{out}}
<pre>Move disc 1 from pole 1 to pole 3
Move disc 2 from pole 1 to pole 2
Move disc 1 from pole 3 to pole 2
Move disc 3 from pole 1 to pole 3
Move disc 1 from pole 2 to pole 1
Move disc 2 from pole 2 to pole 3
Move disc 1 from pole 1 to pole 3</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay (map showmove (move 4 1 2 3)))]
 
showmove :: (num,num)->[char]
showmove (src,dest)
= "Move disk from pole " ++ show src ++ " to pole " ++ show dest
 
move :: num->*->*->*->[(*,*)]
move n src via dest
= [], if n=0
= left ++ [(src,dest)] ++ right, otherwise
where left = move (n-1) src dest via
right = move (n-1) via src dest</syntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3</pre>
 
=={{header|MIPS Assembly}}==
Line 2,510 ⟶ 4,397:
hanoi(3)
--><langsyntaxhighlight lang="mips">
# Towers of Hanoi
# MIPS assembly implementation (tested with MARS)
Line 2,612 ⟶ 4,499:
beq $s0, $t1, exithanoi
j recur2
</syntaxhighlight>
</lang>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">^ 2 x^y П0 <-> 2 / {x} x#0 16
3 П3 2 П2 БП 20 3 П2 2 П3
1 П1 ПП 25 КППB ПП 28 КППA ПП 31
Line 2,623 ⟶ 4,510:
ИП2 ИП1 КППC ИП1 ИП2 ИП3 П1 -> П3 ->
П2 В/О 1 0 / + С/П КИП0 ИП0 x=0
89 3 3 1 ИНВ ^ ВП 2 С/П В/О</langsyntaxhighlight>
 
Instruction: РA = 56; РB = 60; РC = 72; N В/О С/П, where 2 <= N <= 7.
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Towers;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
Line 2,647 ⟶ 4,534:
 
ReadChar
END Towers.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Hanoi EXPORTS Main;
 
FROM IO IMPORT Put;
Line 2,666 ⟶ 4,553:
BEGIN
doHanoi(4, 1, 2, 3);
END Hanoi.</langsyntaxhighlight>
 
=={{header|Monte}}==
<langsyntaxhighlight lang="monte">def move(n, fromPeg, toPeg, viaPeg):
if (n > 0):
move(n.previous(), fromPeg, viaPeg, toPeg)
Line 2,675 ⟶ 4,562:
move(n.previous(), viaPeg, toPeg, fromPeg)
 
move(3, "left", "right", "middle")</langsyntaxhighlight>
 
=={{header|MoonScript}}==
<syntaxhighlight lang="moonscript">hanoi = (n, src, dest, via) ->
if n > 1
hanoi n-1, src, via, dest
print "#{src} -> #{dest}"
if n > 1
hanoi n-1, via, dest, src
 
hanoi 4,1,3,2</syntaxhighlight>
{{Out}}
<pre>1 -> 2
1 -> 3
2 -> 3
1 -> 2
3 -> 1
3 -> 2
1 -> 2
1 -> 3
2 -> 3
2 -> 1
3 -> 1
2 -> 3
1 -> 2
1 -> 3
2 -> 3</pre>
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 2,697 ⟶ 4,609:
Hanoi(4)
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 2,706 ⟶ 4,618:
return
 
-- 09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
parse arg discs .
Line 2,715 ⟶ 4,627:
return
 
-- 09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)09:02, 27 August 2022 (UTC)~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method move(discs = int 4, towerFrom = int 1, towerTo = int 2, towerVia = int 3, moves = int 0) public static
if discs == 1 then do
Line 2,727 ⟶ 4,639:
end
return moves
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,750 ⟶ 4,662:
 
=={{header|NewLISP}}==
<langsyntaxhighlight lang="lisp">(define (move n from to via)
(if (> n 0)
(move (- n 1) from via to
Line 2,756 ⟶ 4,668:
(move (- n 1) via to from))))
 
(move 4 1 2 3)</langsyntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang Python="python">proc hanoi(disks: int,; fromTower: string, toTower: string, viaTower: string) =
if disks != 0:
hanoi(disks - 1, fromTower, viaTower, toTower)
Line 2,765 ⟶ 4,677:
hanoi(disks - 1, viaTower, toTower, fromTower)
hanoi(4, "1", "2", "3")</langsyntaxhighlight>
{{out}}
<pre>Move disk 1 from 1 to 3
Line 2,782 ⟶ 4,694:
Move disk 2 from 1 to 2
Move disk 1 from 3 to 2</pre>
 
=={{header|Oberon-2}}==
{{trans|C}}
<syntaxhighlight lang="oberon2">MODULE Hanoi;
 
IMPORT Out;
 
PROCEDURE Move(n,from,via,to:INTEGER);
BEGIN
IF n > 1 THEN
Move(n-1,from,to,via);
Out.String("Move disk from pole ");
Out.Int(from,0);
Out.String(" to pole ");
Out.Int(to,0);
Out.Ln;
Move(n-1,via,from,to);
ELSE
Out.String("Move disk from pole ");
Out.Int(from,0);
Out.String(" to pole ");
Out.Int(to,0);
Out.Ln;
END;
END Move;
BEGIN
Move(4,1,2,3);
END Hanoi.
</syntaxhighlight>
 
{{out}}
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class Hanoi {
function : Main(args : String[]) ~ Nil {
Move(4, 1, 2, 3);
Line 2,799 ⟶ 4,759:
};
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Line 2,808 ⟶ 4,768:
 
The Interface - TowersOfHanoi.h:
<langsyntaxhighlight lang="objc">#import <Foundation/NSObject.h>
 
@interface TowersOfHanoi: NSObject {
Line 2,819 ⟶ 4,779:
-(void) setPegFrom: (int) from andSetPegTo: (int) to andSetPegVia: (int) via andSetNumDisks: (int) disks;
-(void) movePegFrom: (int) from andMovePegTo: (int) to andMovePegVia: (int) via andWithNumDisks: (int) disks;
@end</langsyntaxhighlight>
The Implementation - TowersOfHanoi.m:
<langsyntaxhighlight lang="objc">#import "TowersOfHanoi.h"
@implementation TowersOfHanoi
 
Line 2,841 ⟶ 4,801:
}
 
@end</langsyntaxhighlight>
Test code: TowersTest.m:
<langsyntaxhighlight lang="objc">#import <stdio.h>
#import "TowersOfHanoi.h"
 
Line 2,862 ⟶ 4,822:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec hanoi n a b c =
if n <> 0 then begin
hanoi (pred n) a c b;
Line 2,873 ⟶ 4,833:
 
let () =
hanoi 4 1 2 3</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">function hanoimove(ndisks, from, to, via)
if ( ndisks == 1 )
printf("Move disk from pole %d to pole %d\n", from, to);
Line 2,886 ⟶ 4,846:
endfunction
 
hanoimove(4, 1, 2, 3);</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: move(n, from, to, via)
n 0 > ifTrue: [
move(n 1-, from, via, to)
Line 2,897 ⟶ 4,857:
] ;
 
5 $left $middle $right) move </langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
proc {TowersOfHanoi N From To Via}
if N > 0 then
Line 2,909 ⟶ 4,869:
end
in
{TowersOfHanoi 4 left middle right}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{trans|Python}}
 
<langsyntaxhighlight lang="parigp">\\ Towers of Hanoi
\\ 8/19/2016 aev
\\ Where: n - number of disks, sp - start pole, ep - end pole.
Line 2,925 ⟶ 4,885:
}
\\ Testing n=3:
HanoiTowers(3,1,3);</langsyntaxhighlight>
 
{{Output}}
Line 2,942 ⟶ 4,902:
{{works with|Free Pascal|2.0.4}}
I think it is standard pascal, except for the constant array "strPole". I am not sure if constant arrays are part of the standard. However, as far as I know, they are a "de facto" standard in every compiler.
<langsyntaxhighlight lang="pascal">program Hanoi;
type
TPole = (tpLeft, tpCenter, tpRight);
Line 2,959 ⟶ 4,919:
begin
MoveStack(4,tpLeft,tpCenter,tpRight);
end.</langsyntaxhighlight>
A little longer, but clearer for my taste
<langsyntaxhighlight lang="pascal">program Hanoi;
type
TPole = (tpLeft, tpCenter, tpRight);
Line 2,985 ⟶ 4,945:
begin
MoveStack(4,tpLeft,tpCenter,tpRight);
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub hanoi {
my ($n, $from, $to, $via) = (@_, 1, 2, 3);
 
Line 2,998 ⟶ 4,958:
hanoi($n - 1, $via, $to, $from);
};
};</langsyntaxhighlight>
 
=={{header|Perl 6}}==
<lang perl6>subset Peg of Int where 1|2|3;
 
multi hanoi (0, Peg $a, Peg $b, Peg $c) { }
multi hanoi (Int $n, Peg $a = 1, Peg $b = 2, Peg $c = 3) {
hanoi $n - 1, $a, $c, $b;
say "Move $a to $b.";
hanoi $n - 1, $c, $b, $a;
}</lang>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant poles = {"left","middle","right"}
<span style="color: #008080;">constant</span> <span style="color: #000000;">poles</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"left"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"middle"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"right"</span><span style="color: #0000FF;">}</span>
enum left, middle, right
<span style="color: #008080;">enum</span> <span style="color: #000000;">left</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">middle</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">right</span>
 
sequence disks
<span style="color: #004080;">sequence</span> <span style="color: #000000;">disks</span>
integer moves
<span style="color: #004080;">integer</span> <span style="color: #000000;">moves</span>
procedure showpegs(integer src, integer dest)
string desc = sprintf("%s to %s:",{poles[src],poles[dest]})
<span style="color: #008080;">procedure</span> <span style="color: #000000;">showpegs</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">src</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">dest</span><span style="color: #0000FF;">)</span>
disks[dest] &= disks[src][$]
<span style="color: #004080;">string</span> <span style="color: #000000;">desc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%s to %s:"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">poles</span><span style="color: #0000FF;">[</span><span style="color: #000000;">src</span><span style="color: #0000FF;">],</span><span style="color: #000000;">poles</span><span style="color: #0000FF;">[</span><span style="color: #000000;">dest</span><span style="color: #0000FF;">]})</span>
disks[src] = disks[src][1..$-1]
<span style="color: #000000;">disks</span><span style="color: #0000FF;">[</span><span style="color: #000000;">dest</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">disks</span><span style="color: #0000FF;">[</span><span style="color: #000000;">src</span><span style="color: #0000FF;">][$]</span>
for i=1 to length(disks) do
<span style="color: #000000;">disks</span><span style="color: #0000FF;">[</span><span style="color: #000000;">src</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">disks</span><span style="color: #0000FF;">[</span><span style="color: #000000;">src</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
printf(1,"%-16s | %s\n",{desc,join(sq_add(disks[i],'0'),' ')})
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">disks</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
desc = ""
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%-16s | %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">desc</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">disks</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">),</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">)})</span>
end for
<span style="color: #000000;">desc</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
printf(1,"\n")
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
moves += 1
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #000000;">moves</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
procedure hanoir(integer n, src=left, dest=right, via=middle)
if n>0 then
<span style="color: #008080;">procedure</span> <span style="color: #000000;">hanoir</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">src</span><span style="color: #0000FF;">=</span><span style="color: #000000;">left</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dest</span><span style="color: #0000FF;">=</span><span style="color: #000000;">right</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">via</span><span style="color: #0000FF;">=</span><span style="color: #000000;">middle</span><span style="color: #0000FF;">)</span>
hanoir(n-1, src, via, dest)
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
showpegs(src,dest)
<span style="color: #000000;">hanoir</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">src</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">via</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dest</span><span style="color: #0000FF;">)</span>
hanoir(n-1, via, dest, src)
<span style="color: #000000;">showpegs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">src</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dest</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #000000;">hanoir</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">via</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dest</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">src</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
procedure hanoi(integer n)
disks = {reverse(tagset(n)),{},{}}
<span style="color: #008080;">procedure</span> <span style="color: #000000;">hanoi</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
moves = 0
<span style="color: #000000;">disks</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)),{},{}}</span>
hanoir(n)
<span style="color: #000000;">moves</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
printf(1,"completed in %d moves\n",{moves})
<span style="color: #000000;">hanoir</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"completed in %d moves\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">moves</span><span style="color: #0000FF;">})</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
hanoi(3)</lang>
<span style="color: #000000;">hanoi</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (output of 4,5,6 also shown)</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre style="float:left">
Line 3,174 ⟶ 5,127:
{{trans|C}}
 
<langsyntaxhighlight lang="phl">module hanoi;
 
extern printf;
Line 3,189 ⟶ 5,142:
move(4, 1,2,3);
return 0;
]</langsyntaxhighlight>
 
=={{header|PHP}}==
{{trans|Java}}
<langsyntaxhighlight lang="php">function move($n,$from,$to,$via) {
if ($n === 1) {
print("Move disk from pole $from to pole $to");
Line 3,201 ⟶ 5,154:
move($n-1,$via,$to,$from);
}
}</langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
hanoi(3, left, center, right).
 
hanoi(0, _From, _To, _Via) => true.
hanoi(N, From, To, Via) =>
hanoi(N - 1, From, Via, To),
printf("Move disk %w from pole %w to pole %w\n", N, From, To),
hanoi(N - 1, Via, To, From).
</syntaxhighlight>
 
{{out}}
<pre>
Move disk 1 from pole left to pole center
Move disk 2 from pole left to pole right
Move disk 1 from pole center to pole right
Move disk 3 from pole left to pole center
Move disk 1 from pole right to pole left
Move disk 2 from pole right to pole center
Move disk 1 from pole left to pole center
count=7, theoretical=7</pre>
 
===Fast counting===
<syntaxhighlight lang="picat">main =>
hanoi(64).
 
hanoi(N) =>
printf("N=%d\n", N),
Count = move(N, left, center, right) ,
printf("count=%w, theoretical=%w\n", Count, 2**N-1).
table
move(0, _From, _To, _Via) = 0.
move(N, From, To, Via) = Count =>
Count1 = move(N - 1, From, Via, To),
Count2 = move(N - 1, Via, To, From),
Count = Count1+Count2+1.
</syntaxhighlight>
{{out}}
<pre>
N=64
count=18446744073709551615, theoretical=18446744073709551615</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de move (N A B C) # Use: (move 3 'left 'center 'right)
(unless (=0 N)
(move (dec N) A C B)
(println 'Move 'disk 'from A 'to B)
(move (dec N) C B A) ) )</langsyntaxhighlight>
 
=={{header|Pop11}}==
<lang pop11>define hanoi(n, src, dst, via);
if n > 0 then
hanoi(n - 1, src, via, dst);
'Move disk ' >< n >< ' from ' >< src >< ' to ' >< dst >< '.' =>
hanoi(n - 1, via, dst, src);
endif;
enddefine;
 
hanoi(4, "left", "middle", "right");</lang>
 
=={{header|PL/I}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="pli">tower: proc options (main);
 
call Move (4,1,2,3);
Line 3,241 ⟶ 5,226:
end Move;
 
end tower;</langsyntaxhighlight>
 
=={{Headerheader|PlainTeXPL/M}}==
{{Trans|Tiny BASIC}}
Iterative solution as PL/M doesn't do recursion.
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
<syntaxhighlight lang="pli">100H: /* ITERATIVE TOWERS OF HANOI; TRANSLATED FROM TINY BASIC (VIA ALGOL W) */
 
/* CP/M BDOS SYSTEM CALL */
<lang TeX>\newcount\hanoidepth
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* I/O ROUTINES */
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
 
DECLARE ( D, N, X, S, T ) ADDRESS;
/* FIXED NUMBER OF DISCS: 4 */
N = 1;
DO D = 1 TO 4;
N = N + N;
END;
DO X = 1 TO N - 1;
/* AS IN ALGOL W, WE CAN USE PL/M'S BIT ABD MOD OPERATORS */
S = ( X AND ( X - 1 ) ) MOD 3;
T = ( ( X OR ( X - 1 ) ) + 1 ) MOD 3;
CALL PR$STRING( .'MOVE DISC ON PEG $' );
CALL PR$CHAR( '1' + S );
CALL PR$STRING( .' TO PEG $' );
CALL PR$CHAR( '1' + T );
CALL PR$STRING( .( 0DH, 0AH, '$' ) );
END;
EOF</syntaxhighlight>
{{out}}
<pre>
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|PlainTeX}}==
 
<syntaxhighlight lang="tex">\newcount\hanoidepth
\def\hanoi#1{%
\hanoidepth = #1
Line 3,263 ⟶ 5,296:
 
\hanoi{5}
\end</langsyntaxhighlight>
 
=={{header|Pop11}}==
<syntaxhighlight lang="pop11">define hanoi(n, src, dst, via);
if n > 0 then
hanoi(n - 1, src, via, dst);
'Move disk ' >< n >< ' from ' >< src >< ' to ' >< dst >< '.' =>
hanoi(n - 1, via, dst, src);
endif;
enddefine;
 
hanoi(4, "left", "middle", "right");</syntaxhighlight>
 
=={{header|PostScript}}==
A million-page document, each page showing one move.
<langsyntaxhighlight PostScriptlang="postscript">%!PS-Adobe-3.0
%%BoundingBox: 0 0 300 300
 
Line 3,314 ⟶ 5,358:
drawtower 0 1 2 n hanoi
 
%%EOF</langsyntaxhighlight>
 
=={{header|PowerShell}}==
 
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function hanoi($n, $a, $b, $c) {
if($n -eq 1) {
Line 3,330 ⟶ 5,374:
}
hanoi 3 "A" "B" "C"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 3,344 ⟶ 5,388:
=={{header|Prolog}}==
From Programming in Prolog by W.F. Clocksin & C.S. Mellish
<langsyntaxhighlight lang="prolog">hanoi(N) :- move(N,left,center,right).
 
move(0,_,_,_) :- !.
Line 3,353 ⟶ 5,397:
move(M,C,B,A).
 
inform(X,Y) :- write([move,a,disk,from,the,X,pole,to,Y,pole]), nl.</langsyntaxhighlight>
 
Using DCGs and separating core logic from IO
<langsyntaxhighlight lang="prolog">
hanoi(N, Src, Aux, Dest, Moves-NMoves) :-
NMoves is 2^N - 1,
Line 3,374 ⟶ 5,418:
move(1, Src, Aux, Dest),
move(N0, Aux, Src, Dest).
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
Algorithm according to http://en.wikipedia.org/wiki/Towers_of_Hanoi
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Hanoi(n, A.s, C.s, B.s)
If n
Hanoi(n-1, A, B, C)
Line 3,384 ⟶ 5,428:
Hanoi(n-1, B, C, A)
EndIf
EndProcedure</langsyntaxhighlight>
Full program
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Hanoi(n, A.s, C.s, B.s)
If n
Hanoi(n-1, A, B, C)
Line 3,399 ⟶ 5,443:
Hanoi(n,"Left Peg","Middle Peg","Right Peg")
PrintN(#CRLF$+"Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
{{out}}
Moving 3 pegs.
Line 3,415 ⟶ 5,459:
=={{header|Python}}==
===Recursive===
<langsyntaxhighlight lang="python">def hanoi(ndisks, startPeg=1, endPeg=3):
if ndisks:
hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
print (f"Move disk %d{ndisks} from peg %d{startPeg} to peg %d{endPeg}" % (ndisks, startPeg, endPeg)
hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)
 
hanoi(ndisks=4)</langsyntaxhighlight>
{{out}} for ndisks=2
<pre>
Line 3,432 ⟶ 5,476:
Or, separating the definition of the data from its display:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Towers of Hanoi'''
 
 
Line 3,459 ⟶ 5,503:
print(__doc__ + ':\n\n' + '\n'.join(
map(fromTo, hanoi(4)('left')('right')('mid'))
))</langsyntaxhighlight>
{{Out}}
<pre>Towers of Hanoi:
Line 3,483 ⟶ 5,527:
Refactoring the version above to recursively generate a simple visualisation:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Towers of Hanoi'''
 
from itertools import accumulate, chain, repeat
Line 3,490 ⟶ 5,534:
 
 
# hanoi :: Int -> [(StringInt, StringInt)]
def hanoi(n):
'''A list of index pairs, representing disk moves
Line 3,503 ⟶ 5,547:
 
 
# hanoiState :: ([Int],[Int],[Int], String) -> (Int, Int) -> ([Int],[Int],[Int])
# ([Int],[Int],[Int], String)
def hanoiState(tpl, ab):
'''A new Hanoi tower state'''
a, b = ab
xs, ys = tpl[a], tpl[b]
 
w = 3 * (2 + (2 * max(map(max, filter(len, tpl[:-1])))))
 
def delta(i):
Line 3,514 ⟶ 5,561:
) else [xs[0]] + ys
 
returntkns tuple= moveName(map(delta'left', [0'mid', 1, 2]'right'))(ab)
caption = ' '.join(tkns)
return tuple(map(delta, [0, 1, 2])) + (
(caption if tkns[0] != 'mid' else caption.rjust(w, ' ')),
)
 
 
# showHanoi :: ([Int],[Int],[Int], String) -> String
def showHanoi(tpl):
'''StringCaptioned string representation of aan updated Hanoi tower state.'''
 
def fullHeight(n):
Line 3,526 ⟶ 5,577:
mul = curry(operator.mul)
lt = curry(operator.lt)
rods = fmap(fmap(mul('**__')))(
list(tpl[0:3])
)
h = max(map(len, rods))
Line 3,543 ⟶ 5,594:
)(rods))
)
return tpl[3] + '\n\n' + unlines(xs) + '\n' + ('-___' * 3 * w) + (
 
'\n' * 2
 
)
# moveName :: (String, String, String) -> (Int, Int) -> [String]
def moveName(labels):
'''(from, to) index pair represented as an a -> b string.'''
def go(ab):
a, b = ab
return [labels[a], ' to ', labels[b]] if a < b else [
labels[b], ' from ', labels[a]
]
return lambda ab: go(ab)
 
 
Line 3,557 ⟶ 5,617:
fmap(showHanoi)(
scanl(hanoiState)(
(enumFromTo(1)(n), [], [], '')
)(hanoi(n))
)
Line 3,626 ⟶ 5,686:
return lambda a: lambda xs: (
accumulate(chain([a], xs), f)
)
 
 
# showLog :: a -> IO String
def showLog(*s):
'''Arguments printed with
intercalated arrows.'''
print(
' -> '.join(map(str, s))
)
 
Line 3,654 ⟶ 5,723:
# TEST ----------------------------------------------------
if __name__ == '__main__':
main()</langsyntaxhighlight>
<pre>Hanoi sequence for 3 disks:
 
**
****
******
------------------------
 
__
____
______
________________________
left to right
 
****____
******______ **__
________________________
------------------------
left to mid
 
______ ____ __
________________________
mid from right
 
****** **** ** __
______ ____
------------------------
________________________
left to right
 
__
____ ______
________________________
left from mid
 
__ ____ ** ______
________________________
****** ****
mid to right
------------------------
 
____
__ ______
________________________
left to right
 
** __
**** ****** ____
______
------------------------
________________________</pre>
 
==={{libheader|VPython}}===
There is a 3D hanoi-game in the examples that come with VPython,
and at [https://github.com/vpython/visual/blob/master/examples/hanoi.py github].
 
=={{header|Quackery}}==
** **** ******
------------------------
 
<syntaxhighlight lang="quackery"> [ stack ] is rings ( --> [ )
 
[ rings share
****
depth share -
** ******
8 * times sp
------------------------
emit sp emit sp
say 'move' cr ] is echomove ( c c --> )
 
[ dup rings put
depth put
char a char b char c
[ swap decurse
rot 2dup echomove
decurse
swap rot ]
3 times drop
depth release
rings release ] is hanoi ( n --> n )
 
say 'How to solve a three ring Towers of Hanoi puzzle:' cr cr
**
3 hanoi cr</syntaxhighlight>
****
******
------------------------</pre>
 
{{out}}
==={{libheader|VPython}}===
 
There is a 3D hanoi-game in the examples that come with VPython,
<pre>How to solve a three ring Towers of Hanoi puzzle:
and at [https://github.com/vpython/visual/blob/master/examples/hanoi.py github].
 
a c move
a b move
c b move
a c move
b a move
b c move
a c move
a b move
c b move
c a move
b a move
c b move
a c move
a b move
c b move
 
</pre>
 
=={{header|Quite BASIC}}==
'This is implemented on the Quite BASIC website
'http://www.quitebasic.com/prj/puzzle/towers-of-hanoi/
<langsyntaxhighlight Quitelang="quite BASICbasic">1000 REM Towers of Hanoi
1010 REM Quite BASIC Puzzle Project
1020 CLS
Line 3,876 ⟶ 5,992:
9110 REM Restore N before returning
9120 LET N = N + 1
9130 RETURN</langsyntaxhighlight>
 
=={{header|R}}==
{{trans|Octave}}
<langsyntaxhighlight lang="rsplus">hanoimove <- function(ndisks, from, to, via) {
if ( ndisks == 1) ){
cat("move disk from", from, "to", to, "\n")
} else {
hanoimove(ndisks - 1, from, via, to)
hanoimove(1, from, to, via)
hanoimove(ndisks - 1, via, to, from)
}
}
 
hanoimove(4, 1, 2, 3)</langsyntaxhighlight>
 
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define (hanoi n a b c)
Line 3,902 ⟶ 6,017:
(hanoi (- n 1) c b a)))
(hanoi 4 'left 'middle 'right)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>subset Peg of Int where 1|2|3;
 
multi hanoi (0, Peg $a, Peg $b, Peg $c) { }
multi hanoi (Int $n, Peg $a = 1, Peg $b = 2, Peg $c = 3) {
hanoi $n - 1, $a, $c, $b;
say "Move $a to $b.";
hanoi $n - 1, $c, $b, $a;
}</syntaxhighlight>
 
=={{header|Rascal}}==
{{trans|Python}}
<langsyntaxhighlight lang="rascal">public void hanoi(ndisks, startPeg, endPeg){
if(ndisks>0){
hanoi(ndisks-1, startPeg, 6 - startPeg - endPeg);
Line 3,912 ⟶ 6,038:
hanoi(ndisks-1, 6 - startPeg - endPeg, endPeg);
}
}</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="rascal">rascal>hanoi(4,1,3)
Move disk 1 from peg 1 to peg 2
Move disk 2 from peg 1 to peg 3
Line 3,930 ⟶ 6,056:
Move disk 2 from peg 1 to peg 3
Move disk 1 from peg 2 to peg 3
ok</langsyntaxhighlight>
 
=={{header|Raven}}==
{{trans|Python}}
<langsyntaxhighlight lang="raven">define hanoi use ndisks, startpeg, endpeg
ndisks 0 > if
6 startpeg - endpeg - startpeg ndisks 1 - hanoi
Line 3,946 ⟶ 6,072:
# 4 disks
4 dohanoi
</syntaxhighlight>
</lang>
{{out}}
<pre>raven hanoi.rv
Line 3,967 ⟶ 6,093:
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Towers of Hanoi"
URL: http://rosettacode.org/wiki/Towers_of_Hanoi
Line 3,987 ⟶ 6,113:
]
 
hanoi 4</langsyntaxhighlight>
{{out}}
<pre>left -> right
Line 4,005 ⟶ 6,131:
right -> middle</pre>
 
=={{header|RetroRefal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
<lang Retro>4 elements a b c n
= <Move 4 1 2 3>;
};
 
Move {
: vars !c !b !a !n ;
: hanoi ( num from0 toe.X via= -- );
s.N s.Src s.Via s.Dest, <- s.N 1>: s.Next =
vars
<Move s.Next s.Src s.Dest s.Via>
@n 0 <>
<Prout "Move disk from pole" s.Src "to pole" s.Dest>
[
<Move s.Next s.Via s.Src s.Dest>;
@n @a @b @c
};</syntaxhighlight>
@n 1- @a @c @b hanoi
{{out}}
vars
<pre>Move disk from pole 1 to pole 2
@b @a "\nMove a ring from %d to %d" puts
Move disk from @npole 1- @c @bto @apole hanoi3
Move disk from pole 2 to pole 3
] ifTrue ;
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3</pre>
 
=={{header|Retro}}==
4 1 3 2 hanoi</lang>
<syntaxhighlight lang="retro">[[User:Wodan58|Wodan58]] ([[User talk:Wodan58|talk]])
{ 'Num 'From 'To 'Via } [ var ] a:for-each
:set !Via !To !From !Num ;
:display @To @From 'Move_a_ring_from_%n_to_%n\n s:format s:put ;
:hanoi (num,from,to,via-)
set @Num n:-zero?
[ @Num @From @To @Via
@Num n:dec @From @Via @To hanoi set display
@Num n:dec @Via @To @From hanoi ] if ;
#3 #1 #3 #2 hanoi nl
[[User:Wodan58|Wodan58]] ([[User talk:Wodan58|talk]])</syntaxhighlight>
 
=={{header|REXX}}==
===simple text moves===
<langsyntaxhighlight lang="rexx">/*REXX program displays the moves to solve the Tower of Hanoi (with N disks). */
parse arg N . /*get optional number of disks from CL.*/
if N=='' | N=="," then N=3 /*Not specified? Then use the default.*/
Line 4,042 ⟶ 6,196:
call mov 6 - @1 - @2, @2, @3 -1
end
return /* [↑] this subroutine uses recursion.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 4,086 ⟶ 6,240:
 
Also, since the pictorial showing of the moves may be voluminous (especially for a larger number of disks), the move counter is started with the maximum and is the count shown is decremented so the viewer can see how many moves are left to display.
<langsyntaxhighlight lang="rexx">/*REXX program displays the moves to solve the Tower of Hanoi (with N disks). */
parse arg N . /*get optional number of disks from CL.*/
if N=='' | N=="," then N=3 /*Not specified? Then use the default.*/
sw= 80; wp= sw%3 - 1; blanks= left('', wp) /*define some default REXX variables. */
c.1= sw % 3 % 2 /* [↑] SW: assume default Screen Width*/
c.2= sw % 2 - 1 /* ◄─── C.1 C.2 C.2 are the positions*/
c.2= sw % 2 - 1
c.3= sw - 2 - c.1 /* of the 3 columns.*/
c.3= sw - 1 - c.1
#= 0; z= 2**N - 1; moveK=z moveK= z /*#moves; min# of moves; where to move.*/
@abc= 'abcdefghijklmnopqrstuvwxyN' /*dithering chars when many disks used.*/
ebcdic= ('f0f2'x==02) /*determine if EBCDIC or ASCII machine.*/
 
if ebcdic then do; bar= 'bf'x; ar= "df"x; boxendither= 'db9f9caf'x; down= "9a"x
tr= 'bc'x; bl= "ab"x; br= 'bb'x; vert= "fa"x; tl= 'ac'x
end
else do; bar= 'c4'x; ar= "10"x; boxendither= 'b0b1b2db'x; down= "1819"x
tr= 'bf'x; bl= "c0"x; br= 'd9'x; vert= "b3"x; tl= 'da'x
end
 
verts= vert || vert; Tcorners= Tcorners= tl || tr; box = left(dither, 1)
downs= down || down; Bcorners= Bcorners= bl || br; boxChars= dither || @abc
$.= 0; $.1= N; k= N; kk= k + k
box = left(boxen, 1); boxChars= boxen || @abc
$.=0; $.1=N; k=N; kk=k+k
 
do j=1 for N; @.3.j= blanks; @.2.j= blanks; @.1.j= center( copies( box, kk), wp)
if N<=length(boxChars) then @.1.j= translate( @.1.j, , substr( boxChars, kk%2, 1), box)
kk= kk - 2
end /*j*/ /*populate the tower of Hanoi spindles.*/
 
call showTowers; call mov 1,3,N; say
say 'The minimum number of moves to solve a ' N"-disk Tower of Hanoi is " z
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
dsk: parse arg from dest; #= # + 1; pp=
if from==1 then do; pp= overlay(bl, pp, c.1)
pp= overlay(bar, pp, c.1+1, c.dest-c.1-1, bar) || tr
end
if from==2 then do
lpostif dest=min=1 then do; pp= overlay(2tl, dest pp, c.1)
hpost pp=max overlay(2bar, destpp, c.1+1, c.2-c.1-1,bar)||br
if dest==1 then do; pp=overlay(tl, pp, c.1)
pp=overlay(bar, pp, c.1+1, c.2-c.1-1, bar)||br
end
if dest==3 then do; pp= overlay(bl, pp, c.2)
pp= overlay(bar, pp, c.2+1, c.3-c.2-1, bar)||tr
end
end
if from==3 then do; pp= overlay(br, pp, c.3)
pp= overlay(bar, pp, c.dest+1, c.3-c.dest-1, bar)
pp= overlay(tl, pp, c.dest)
end
say translate(pp, downs, Bcorners || Tcorners || bar); say overlay(moveK, pp, 1)
say translate(pp, verts, Tcorners || Bcorners || bar)
say translate(pp, downs, Tcorners || Bcorners || bar); moveK= moveK - 1
$.from= $.from - 1; $.dest= $.dest + 1; _f= $.from + 1; _t= $.dest
@.dest._t= @.from._f; @.from._f= blanks; call showTowers
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
mov: if arg(3)==1 then call dsk arg(1) arg(2)
else do; call mov arg(1), 6 -arg(1) -arg(2), arg(3) -1
call mov arg(1), arg(2), 1
call mov 6 -arg(1) -arg(2), arg(2), arg(3) -1
end /* [↑] The MOV subroutine is recursive, */
return /*it uses no variables, is uses BIFs instead*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
showTowers: do j=N by -1 for N; _=@.1.j @.2.j @.3.j; if _\='' then say _; end; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 4,202 ⟶ 6,353:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
move(4, 1, 2, 3)
 
Line 4,209 ⟶ 6,360:
see "" + src + " to " + dst + nl
move(n - 1, via, dst, src) ok
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
{{trans|Python}}
{{works with|Halcyon Calc|4.2.7}}
≪ → ndisks start end
≪ '''IF''' ndisks '''THEN'''
ndisks 1 - start 6 start - end - '''HANOI'''
start →STR " → " + end →STR +
ndisks 1 - 6 start - end - end '''HANOI'''
'''END'''
≫ ≫ ''''HANOI'''' STO
 
3 1 3 '''HANOI'''
{{out}}
<pre>
7: "1 → 3"
6: "1 → 2"
5: "3 → 2"
4: "1 → 3"
3: "2 → 1"
2: "2 → 3"
1: "1 → 3"
</pre>
 
=={{header|Ruby}}==
===version 1===
<langsyntaxhighlight lang="ruby">def move(num_disks, start=0, target=1, using=2)
if num_disks == 1
@towers[target] << @towers[start].pop
Line 4,226 ⟶ 6,400:
n = 5
@towers = [[*1..n].reverse, [], []]
move(n)</langsyntaxhighlight>
 
{{out}}
Line 4,264 ⟶ 6,438:
 
===version 2===
<langsyntaxhighlight lang="ruby"># solve(source, via, target)
# Example:
# solve([5, 4, 3, 2, 1], [], [])
Line 4,292 ⟶ 6,466:
end
 
solve([5, 4, 3, 2, 1], [], [])</langsyntaxhighlight>
{{out}}
<pre>
Line 4,330 ⟶ 6,504:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">a = move(4, "1", "2", "3")
function move(n, a$, b$, c$)
if n > 0 then
Line 4,337 ⟶ 6,511:
a = move(n-1, b$, a$, c$)
end if
end function</langsyntaxhighlight>
<pre>Move disk from 1 to 3
Move disk from 1 to 2
Line 4,356 ⟶ 6,530:
=={{header|Rust}}==
{{trans|C}}
<langsyntaxhighlight lang="rust">fn move_(n: i32, from: i32, to: i32, via: i32) {
if n > 0 {
move_(n - 1, from, via, to);
Line 4,366 ⟶ 6,540:
fn main() {
move_(4, 1,2,3);
}</langsyntaxhighlight>
 
=={{header|SASL}}==
Copied from SAL manual, Appendix II, answer (3)
<langsyntaxhighlight SASLlang="sasl">hanoi 8 ‘abc"
WHERE
hanoi 0 (a,b,c,) = ()
Line 4,376 ⟶ 6,550:
‘move a disc from " , a , ‘ to " , b , NL ,
hanoi (n-1) (c,b,a)
?</langsyntaxhighlight>
 
=={{header|Sather}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="sather">class MAIN is
move(ndisks, from, to, via:INT) is
Line 4,395 ⟶ 6,569:
move(4, 1, 2, 3);
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def move(n: Int, from: Int, to: Int, via: Int) : Unit = {
if (n == 1) {
Console.println("Move disk from pole " + from + " to pole " + to)
Line 4,406 ⟶ 6,580:
move(n - 1, via, to, from)
}
}</langsyntaxhighlight>
This next example is from http://gist.github.com/66925 it is a translation to Scala of a Prolog solution and solves the problem at compile time
<langsyntaxhighlight lang="scala">object TowersOfHanoi {
import scala.reflect.Manifest
Line 4,443 ⟶ 6,617:
run[_2,Left,Right,Center]
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Recursive Process
<lang scheme>(define (hanoi n a b c)
<syntaxhighlight lang="scheme">(define (towers-of-hanoi n from to spare)
(if (> n 0)
(define (print-move from to)
(begin
(hanoi (- n 1) a cdisplay b"Move[")
(display "Move disk from pole ")
(display a", ")
(display " to pole ")
(display b"]")
(newline))
(hanoicond (-(= n 10) c b a)))"done")
(else
(towers-of-hanoi (- n 1) from spare to)
(print-move from to)
(towers-of-hanoi (- n 1) spare to from))))
 
(towers-of-hanoi 43 1"A" 2"B" 3"C")</langsyntaxhighlight>
{{out}}
<pre>Move[A, B]
Move[A, C]
Move[B, C]
Move[A, B]
Move[C, A]
Move[C, B]
Move[A, B]
"done"</pre>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const proc: hanoi (in integer: disk, in string: source, in string: dest, in string: via) is func
begin
if disk > 0 then
Line 4,467 ⟶ 6,654:
hanoi(pred(disk), via, dest, source);
end if;
end func;</langsyntaxhighlight>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program hanoi;
loop for [src, dest] in move(4, 1, 2, 3) do
print("Move disk from pole " + src + " to pole " + dest);
end loop;
 
proc move(n, src, via, dest);
if n=0 then return []; end if;
return move(n-1, src, dest, via)
+ [[src, dest]]
+ move(n-1, via, src, dest);
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func hanoi(n, from=1, to=2, via=3) {
if (n == 1) {
say "Move disk from pole #{from} to pole #{to}.";
Line 4,481 ⟶ 6,698:
}
 
hanoi(4);</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4">* # Note: count is global
 
define('hanoi(n,src,trg,tmp)') :(hanoi_end)
Line 4,496 ⟶ 6,713:
* # Test with 4 discs
hanoi(4,'A','C','B')
end</langsyntaxhighlight>
{{out}}
<pre>1: Move disc from A to B
Line 4,513 ⟶ 6,730:
14: Move disc from A to C
15: Move disc from B to C</pre>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "hanoi" )
@( description, "Solve the Towers of Hanoi problem with recursion." )
@( see_also, "https://rosettacode.org/wiki/Towers_of_Hanoi" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure hanoi is
type pegs is (left, center, right);
 
-- Determine the moves
 
procedure solve( num_disks : natural; start_peg : pegs; end_peg : pegs; via_peg : pegs ) is
begin
if num_disks > 0 then
solve( num_disks - 1, start_peg, via_peg, end_peg );
put( "Move disk" )@( num_disks )@( " from " )@( start_peg )@( " to " )@( end_peg );
new_line;
solve( num_disks - 1, via_peg, end_peg, start_peg );
end if;
end solve;
 
begin
-- solve with 4 disks at the left
--solve( 4, left, right, center );
solve( 4, left, right, center );
put_line( "Towers of Hanoi puzzle completed" );
end hanoi;</syntaxhighlight>
 
=={{header|Standard ML}}==
fun hanoi(0, a, b, c) = [] |
Line 4,519 ⟶ 6,770:
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">function hanoi(n, a, b, c) {
if (n>0) {
hanoi(n-1, a, c, b)
Line 4,535 ⟶ 6,786:
Move from 3 to 1
Move from 3 to 2
Move from 1 to 2</langsyntaxhighlight>
 
=={{header|Swift}}==
{{trans|JavaScript}}
<langsyntaxhighlight Swiftlang="swift">func hanoi(n:Int, a:String, b:String, c:String) {
if (n > 0) {
hanoi(n - 1, a, c, b)
Line 4,547 ⟶ 6,798:
}
 
hanoi(4, "A", "B", "C")</langsyntaxhighlight>
 
'''Swift 2.1'''
<langsyntaxhighlight Swiftlang="swift">func hanoi(n:Int, a:String, b:String, c:String) {
if (n > 0) {
hanoi(n - 1, a: a, b: c, c: b)
Line 4,558 ⟶ 6,809:
}
hanoi(4, a:"A", b:"B", c:"C")</langsyntaxhighlight>
 
=={{header|Tcl}}==
The use of <code>interp alias</code> shown is a sort of closure: keep track of the number of moves required
<langsyntaxhighlight lang="tcl">interp alias {} hanoi {} do_hanoi 0
 
proc do_hanoi {count n {from A} {to C} {via B}} {
Line 4,576 ⟶ 6,827:
}
 
hanoi 4</langsyntaxhighlight>
{{out}}
<pre>1: move from A to B
Line 4,596 ⟶ 6,847:
=={{header|TI-83 BASIC}}==
TI-83 BASIC lacks recursion, so technically this task is impossible, however here is a version that uses an iterative method.
<langsyntaxhighlight lang="ti-83b">PROGRAM:TOHSOLVE
0→A
1→B
Line 4,677 ⟶ 6,928:
 
End
</syntaxhighlight>
</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 BASIC hasn't got them natively.
 
<syntaxhighlight lang="tinybasic"> 5 PRINT "How many disks?"
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 = 0 THEN RETURN
GOTO 55</syntaxhighlight>
 
{{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}}==
<langsyntaxhighlight lang="toka">value| sa sb sc n |
[ to sc to sb to sa to n ] is vars!
[ ( num from to via -- )
Line 4,692 ⟶ 7,014:
n 1- sc sb sa recurse
] ifTrue
] is hanoi</langsyntaxhighlight>
 
 
=={{header|True BASIC}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic">
DECLARE SUB hanoi
 
SUB hanoi(n, desde , hasta, via)
IF n > 0 THEN
CALL hanoi(n - 1, desde, via, hasta)
PRINT "Mover disco"; n; "desde posición"; desde; "hasta posición"; hasta
CALL hanoi(n - 1, via, hasta, desde)
END IF
END SUB
 
PRINT "Tres discos"
PRINT
CALL hanoi(3, 1, 2, 3)
PRINT
PRINT "Cuatro discos"
PRINT
CALL hanoi(4, 1, 2, 3)
PRINT
PRINT "Pulsa un tecla para salir"
END
</syntaxhighlight>
 
 
=={{header|TSE SAL}}==
<langsyntaxhighlight TSESALlang="tsesal">// library: program: run: towersofhanoi: recursive: sub <description></description> <version>1.0.0.0.0</version> <version control></version control> (filenamemacro=runprrsu.s) [kn, ri, tu, 07-02-2012 19:54:23]
PROC PROCProgramRunTowersofhanoiRecursiveSub( INTEGER totalDiskI, STRING fromS, STRING toS, STRING viaS, INTEGER bufferI )
IF ( totalDiskI == 0 )
Line 4,719 ⟶ 7,068:
IF ( NOT ( Ask( "program: run: towersofhanoi: recursive: totalDiskI = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
PROCProgramRunTowersofhanoiRecursive( Val( s1 ), "source", "target", "via" )
END</langsyntaxhighlight>
 
=={{header|uBasic/4tH}}==
{{trans|C}}
<syntaxhighlight lang="text">Proc _Move(4, 1,2,3) ' 4 disks, 3 poles
End
 
Line 4,732 ⟶ 7,081:
Proc _Move (a@ - 1, d@, c@, b@)
EndIf
Return</langsyntaxhighlight>
=={{header|UNIX Shell}}==
{{works with|bash}}
<lang bash>#!/bin/bash
 
=={{header|Uiua}}==
move()
{{works with|Uiua|0.10.0}}
{
<syntaxhighlight lang="bash">
local n="$1"
F ← |1.0 (
local from="$2"
local to="$3"
&p ⊏[1 2] &pf "Move disc [from to]: "
local via="$4"
| F⍜(⊡0|-1)⍜(⊏[2 3]|⇌).
F⍜(⊡0|1◌).
F⍜(⊡0|-1)⍜(⊏[1 3]|⇌)
⟩≠1⊢.
)
F [4 1 2 3]
</syntaxhighlight>
{{out}}
<pre>
Move disc [from to]: [1 3]
Move disc [from to]: [1 2]
Move disc [from to]: [3 2]
Move disc [from to]: [1 3]
Move disc [from to]: [2 1]
Move disc [from to]: [2 3]
Move disc [from to]: [1 3]
Move disc [from to]: [1 2]
Move disc [from to]: [3 2]
Move disc [from to]: [3 1]
Move disc [from to]: [2 1]
Move disc [from to]: [3 2]
Move disc [from to]: [1 3]
Move disc [from to]: [1 2]
Move disc [from to]: [3 2]
</pre>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Z Shell}}
<syntaxhighlight lang="bash">function move {
typeset -i n=$1
typeset from=$2
typeset to=$3
typeset via=$4
 
if [[(( "$n" ==)); "1" ]]then
move $(( n - 1 )) "$from" "$via" "$to"
then
echo "Move disk from pole $from to pole $to"
move $(( n - 1 )) "$via" "$to" "$from"
else
move $(($n - 1)) $from $via $to
move 1 $from $to $via
move $(($n - 1)) $via $to $from
fi
}
move "$1 $2 $3 $4@"</langsyntaxhighlight>
 
A strict POSIX (or just really old) shell has no subprogram capability, but scripts are naturally reentrant, so:
{{works with|Bourne Shell}}
{{works with|Almquist Shell}}
<syntaxhighlight lang="bash">#!/bin/sh
if [ "$1" -gt 0 ]; then
"$0" "`expr $1 - 1`" "$2" "$4" "$3"
echo "Move disk from pole $2 to pole $3"
"$0" "`expr $1 - 1`" "$4" "$3" "$2"
fi
</syntaxhighlight>
 
Output from any of the above:
{{Out}}
<pre>$ hanoi 4 1 3 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3</pre>
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import nat
 
move = ~&al^& ^rlPlrrPCT/~&arhthPX ^|W/~& ^|G/predecessor ^/~&htxPC ~&zyxPC
Line 4,763 ⟶ 7,171:
#show+
 
main = ^|T(~&,' -> '--)* move/4 <'start','end','middle'></langsyntaxhighlight>
{{out}}
<pre>start -> middle
Line 4,780 ⟶ 7,188:
start -> end
middle -> end</pre>
 
=={{header|Uxntal}}==
<syntaxhighlight lang="Uxntal">|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1
 
|0100 ( -> )
#0102 [ LIT2 03 &count 04 ] hanoi
POP2 POP2 BRK
 
@hanoi ( from spare to count -: from spare to count )
( moving 0 disks is no-op )
DUP ?{ JMP2r }
 
( move disks 1..count-1 to the spare peg )
#01 SUB ROT SWP hanoi
( from to spare count-1 )
 
( print the current move )
;dict/move print-str
INCk #30 ORA .Console/write DEO
STH2
;dict/from print-str
OVR #30 ORA .Console/write DEO
;dict/to print-str
DUP #30 ORA .Console/write DEO
[ LIT2 0a -Console/write ] DEO
STH2r
 
( move disks 1..count-1 from the spare peg to the goal peg )
STH ROT ROT STHr hanoi
 
( restore original parameters for convenient recursion )
STH2 SWP STH2r INC
 
JMP2r
 
@print-str
&loop
LDAk .Console/write DEO
INC2 LDAk ?&loop
POP2 JMP2r
 
@dict
&move "Move 20 "disk 2000
&from 20 "from 20 "pole 2000
&to 20 "to 20 "pole 2000</syntaxhighlight>
 
=={{header|VBScript}}==
Derived from the BASIC256 version.
<langsyntaxhighlight VBScriptlang="vbscript">Sub Move(n,fromPeg,toPeg,viaPeg)
If n > 0 Then
Move n-1, fromPeg, viaPeg, toPeg
Line 4,793 ⟶ 7,246:
 
Move 4,1,2,3
WScript.StdOut.Write("Towers of Hanoi puzzle completed!")</langsyntaxhighlight>
 
{{out}}
Line 4,815 ⟶ 7,268:
=={{header|Vedit macro language}}==
This implementation outputs the results in current edit buffer.
<langsyntaxhighlight lang="vedit">#1=1; #2=2; #3=3; #4=4 // move 4 disks from 1 to 2
Call("MOVE_DISKS")
Return
Line 4,839 ⟶ 7,292:
Num_Pop(1,4)
}
Return</langsyntaxhighlight>
 
=={{header|Vim Script}}==
<syntaxhighlight lang="vimscript">function TowersOfHanoi(n, from, to, via)
if (a:n > 1)
call TowersOfHanoi(a:n-1, a:from, a:via, a:to)
endif
echom("Move a disc from " . a:from . " to " . a:to)
if (a:n > 1)
call TowersOfHanoi(a:n-1, a:via, a:to, a:from)
endif
endfunction
 
call TowersOfHanoi(4, 1, 3, 2)</syntaxhighlight>
 
{{Out}}
<pre>Move a disc from 1 to 2
Move a disc from 1 to 3
Move a disc from 2 to 3
Move a disc from 1 to 2
Move a disc from 3 to 1
Move a disc from 3 to 2
Move a disc from 1 to 2
Move a disc from 1 to 3
Move a disc from 2 to 3
Move a disc from 2 to 1
Move a disc from 3 to 1
Move a disc from 2 to 3
Move a disc from 1 to 2
Move a disc from 1 to 3
Move a disc from 2 to 3</pre>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Module TowersOfHanoi
Sub MoveTowerDisks(ByVal disks As Integer, ByVal fromTower As Integer, ByVal toTower As Integer, ByVal viaTower As Integer)
If disks > 0 Then
Line 4,854 ⟶ 7,337:
MoveTowerDisks(4, 1, 2, 3)
End Sub
End Module</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Zig">
fn main() {
hanoi(4, "A", "B", "C")
}
 
fn hanoi(n u64, a string, b string, c string) {
if n > 0 {
hanoi(n - 1, a, c, b)
println("Move disk from ${a} to ${c}")
hanoi(n - 1, b, a, c)
}
}
</syntaxhighlight>
 
{{out}}
<pre>
Move disk from A to B
Move disk from A to C
Move disk from B to C
Move disk from A to B
Move disk from C to A
Move disk from C to B
Move disk from A to B
Move disk from A to C
Move disk from B to C
Move disk from B to A
Move disk from C to A
Move disk from B to C
Move disk from A to B
Move disk from A to C
Move disk from B to C
</pre>
 
=={{header|VTL-2}}==
VTL-2 doesn't have procedure parameters, so this stacks and unstacks the return line number and parameters as reuired. The "move" routune starts at line 2000, the routine at 4000 stacks the return line number and parameters for "move" and the routine at 5000 unstacks the return line number and parameters.
<syntaxhighlight lang="vtl2">1000 N=4
1010 F=1
1020 T=2
1030 V=3
1040 S=0
1050 #=2000
1060 #=9999
2000 R=!
2010 #=N<1*2210
2020 #=4000
2030 N=N-1
2040 A=T
2050 T=V
2060 V=A
2070 #=2000
2080 #=5000
2090 ?="Move disk from peg: ";
2100 ?=F
2110 ?=" to peg: ";
2120 ?=T
2130 ?=""
2140 #=4000
2150 N=N-1
2160 A=F
2170 F=V
2180 V=A
2190 #=2000
2200 #=5000
2210 #=R
4000 S=S+1
4010 :S)=R
4020 S=S+1
4030 :S)=N
4040 S=S+1
4050 :S)=F
4060 S=S+1
4070 :S)=V
4080 S=S+1
4090 :S)=T
4100 #=!
5000 T=:S)
5010 S=S-1
5020 V=:S)
5030 S=S-1
5040 F=:S)
5050 S=S-1
5060 N=:S)
5070 S=S-1
5080 R=:S)
5090 S=S-1
5100 #=!</syntaxhighlight>
{{out}}
<pre>
Move disk from peg: 1 to peg: 3
Move disk from peg: 1 to peg: 2
Move disk from peg: 3 to peg: 2
Move disk from peg: 1 to peg: 3
Move disk from peg: 2 to peg: 1
Move disk from peg: 2 to peg: 3
Move disk from peg: 1 to peg: 3
Move disk from peg: 1 to peg: 2
Move disk from peg: 3 to peg: 2
Move disk from peg: 3 to peg: 1
Move disk from peg: 2 to peg: 1
Move disk from peg: 3 to peg: 2
Move disk from peg: 1 to peg: 3
Move disk from peg: 1 to peg: 2
Move disk from peg: 3 to peg: 2
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">class Hanoi {
construct new(disks) {
_moves = 0
System.print("Towers of Hanoi with %(disks) disks:\n")
move(disks, "L", "C", "R")
System.print("\nCompleted in %(_moves) moves\n")
}
 
move(n, from, to, via) {
if (n > 0) {
move(n - 1, from, via, to)
_moves = _moves + 1
System.print("Move disk %(n) from %(from) to %(to)")
move(n - 1, via, to, from)
}
}
}
 
Hanoi.new(3)
Hanoi.new(4)</syntaxhighlight>
 
{{out}}
<pre>
Towers of Hanoi with 3 disks:
 
Move disk 1 from L to C
Move disk 2 from L to R
Move disk 1 from C to R
Move disk 3 from L to C
Move disk 1 from R to L
Move disk 2 from R to C
Move disk 1 from L to C
 
Completed in 7 moves
 
Towers of Hanoi with 4 disks:
 
Move disk 1 from L to R
Move disk 2 from L to C
Move disk 1 from R to C
Move disk 3 from L to R
Move disk 1 from C to L
Move disk 2 from C to R
Move disk 1 from L to R
Move disk 4 from L to C
Move disk 1 from R to C
Move disk 2 from R to L
Move disk 1 from C to L
Move disk 3 from R to C
Move disk 1 from L to R
Move disk 2 from L to C
Move disk 1 from R to C
 
Completed in 15 moves
</pre>
 
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Hanoi"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
DECLARE FUNCTION Hanoi(n, desde , hasta, via)
 
FUNCTION Entry ()
PRINT "Three disks\n"
Hanoi (3, 1, 2, 3)
PRINT "\nFour discks\n"
Hanoi (4, 1, 2, 3)
PRINT "\nTowers of Hanoi puzzle completed!"
END FUNCTION
 
FUNCTION Hanoi (n, desde , hasta, via)
IF n > 0 THEN
Hanoi (n - 1, desde, via, hasta)
PRINT "Move disk"; n; " from pole"; desde; " to pole"; hasta
Hanoi (n - 1, via, hasta, desde)
END IF
END FUNCTION
END PROGRAM</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Text=12;
 
proc MoveTower(Discs, From, To, Using);
Line 4,869 ⟶ 7,543:
];
 
MoveTower(3, "left", "right", "center")</langsyntaxhighlight>
 
{{out}}
Line 4,881 ⟶ 7,555:
Move from left peg to right peg.
</pre>
 
=={{header|XSLT}}==
<lang xml><xsl:template name="hanoi">
<xsl:param name="n"/>
<xsl:param name="from">left</xsl:param>
<xsl:param name="to">middle</xsl:param>
<xsl:param name="via">right</xsl:param>
<xsl:if test="$n &gt; 0">
<xsl:call-template name="hanoi">
<xsl:with-param name="n" select="$n - 1"/>
<xsl:with-param name="from" select="$from"/>
<xsl:with-param name="to" select="$via"/>
<xsl:with-param name="via" select="$to"/>
</xsl:call-template>
<fo:block>
<xsl:text>Move disk from </xsl:text>
<xsl:value-of select="$from"/>
<xsl:text> to </xsl:text>
<xsl:value-of select="$to"/>
</fo:block>
<xsl:call-template name="hanoi">
<xsl:with-param name="n" select="$n - 1"/>
<xsl:with-param name="from" select="$via"/>
<xsl:with-param name="to" select="$to"/>
<xsl:with-param name="via" select="$from"/>
</xsl:call-template>
</xsl:if>
</xsl:template></lang>
 
<xsl:call-template name="hanoi"><xsl:with-param name="n" select="4"/></xsl:call-template>
 
=={{header|XQuery}}==
<langsyntaxhighlight lang="xquery">declare function local:hanoi($disk as xs:integer, $from as xs:integer,
$to as xs:integer, $via as xs:integer) as element()*
{
Line 4,929 ⟶ 7,573:
local:hanoi(4, 1, 2, 3)
}
</hanoi></langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="xml"><?xml version="1.0" encoding="UTF-8"?>
<hanoi>
<move disk="1">
Line 4,993 ⟶ 7,637:
<to>2</to>
</move>
</hanoi></langsyntaxhighlight>
 
=={{header|XSLT}}==
<syntaxhighlight lang="xml"><xsl:template name="hanoi">
<xsl:param name="n"/>
<xsl:param name="from">left</xsl:param>
<xsl:param name="to">middle</xsl:param>
<xsl:param name="via">right</xsl:param>
<xsl:if test="$n &gt; 0">
<xsl:call-template name="hanoi">
<xsl:with-param name="n" select="$n - 1"/>
<xsl:with-param name="from" select="$from"/>
<xsl:with-param name="to" select="$via"/>
<xsl:with-param name="via" select="$to"/>
</xsl:call-template>
<fo:block>
<xsl:text>Move disk from </xsl:text>
<xsl:value-of select="$from"/>
<xsl:text> to </xsl:text>
<xsl:value-of select="$to"/>
</fo:block>
<xsl:call-template name="hanoi">
<xsl:with-param name="n" select="$n - 1"/>
<xsl:with-param name="from" select="$via"/>
<xsl:with-param name="to" select="$to"/>
<xsl:with-param name="via" select="$from"/>
</xsl:call-template>
</xsl:if>
</xsl:template></syntaxhighlight>
 
<xsl:call-template name="hanoi"><xsl:with-param name="n" select="4"/></xsl:call-template>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub hanoi(ndisks, startPeg, endPeg)
if ndisks then
hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
Line 5,025 ⟶ 7,699:
print "Hanoi 2 ellapsed ... ";
hanoi2(22, 1, 3, 2)
print peek("millisrunning") - t2, " ms"</langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
{{works with|CP/M 3.1|YAZE-AG-2.51.2 Z80 emulator}}
{{works with|ZSM4 macro assembler|YAZE-AG-2.51.2 Z80 emulator}}
Use the /S8 switch on the ZSM4 assembler for 8 significant characters for labels and names<br><br>
<syntaxhighlight lang="z80">
;
; Towers of Hanoi using Z80 assembly language
;
; Runs under CP/M 3.1 on YAZE-AG-2.51.2 Z80 emulator
; Assembled with zsm4 on same emulator/OS, uses macro capabilities of said assembler
; Created with vim under Windows
;
; 2023-05-29 Xorph
;
 
;
; Useful definitions
;
 
bdos equ 05h ; Call to CP/M BDOS function
strdel equ 6eh ; Set string delimiter
wrtstr equ 09h ; Write string to console
 
nul equ 00h ; ASCII control characters
cr equ 0dh
lf equ 0ah
 
cnull equ '0' ; ASCII character constants
ca equ 'A'
cb equ 'B'
cc equ 'C'
 
disks equ 4 ; Number of disks to move
 
;
; Macros for BDOS calls
;
 
setdel macro char ; Set string delimiter to char
ld c,strdel
ld e,char
call bdos
endm
 
print macro msg ; Output string to console
ld c,wrtstr
ld de,msg
call bdos
endm
 
pushall macro ; Save required registers to stack
push af
push bc
push de
endm
 
popall macro ; Recall required registers from stack
pop de
pop bc
pop af
endm
 
;
; =====================
; Start of main program
; =====================
;
 
cseg
 
setdel nul ; Set string delimiter to 00h
 
ld a,disks ; Initialization:
ld b,ca ; Tower A is source
ld c,cb ; Tower B is target
ld d,cc ; Tower C is intermediate
 
hanoi:
;
; Parameters in registers:
; Move a disks from b (source) to c (target) via d (intermediate)
;
 
or a ; If 0 disks to move, return
ret z
 
dec a ; Move all but lowest disk from source to intermediate via target
pushall ; Save registers
ld e,c ; Exchange c and d (target and intermediate)
ld c,d
ld d,e
call hanoi ; First recursion
popall ; Restore registers
 
ld hl,source ; Print move of lowest disk from source to target, save registers during BDOS call
ld (hl),b ; Source is still in b
ld hl,target
ld (hl),c ; Target is back in c due to popall
 
pushall
print movement
popall
 
ld e,b ; Now move stack from intermediate to target via source
ld b,d ; Source is still in b, target in c and intermediate in d
ld d,e
jr hanoi ; Optimize tail recursion
 
;
; ================
; Data definitions
; ================
;
 
dseg
 
movement:
defb 'Move disk from tower '
source:
defs 1
defb ' to tower '
target:
defs 1
crlf:
defb cr,lf,nul
 
</syntaxhighlight>
 
{{out}}
<pre>
E>hanoi
Move disk from tower A to tower C
Move disk from tower A to tower B
Move disk from tower C to tower B
Move disk from tower A to tower C
Move disk from tower B to tower A
Move disk from tower B to tower C
Move disk from tower A to tower C
Move disk from tower A to tower B
Move disk from tower C to tower B
Move disk from tower C to tower A
Move disk from tower B to tower A
Move disk from tower C to tower B
Move disk from tower A to tower C
Move disk from tower A to tower B
Move disk from tower C to tower B
 
E>
</pre>
 
=={{header|Zig}}==
{{trans|C}}
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn print(from: u32, to: u32) void {
std.log.info("Moving disk from rod {} to rod {}", .{ from, to });
}
 
pub fn move(n: u32, from: u32, via: u32, to: u32) void {
if (n > 1) {
move(n - 1, from, to, via);
print(from, to);
move(n - 1, via, from, to);
} else {
print(from, to);
}
}
 
pub fn main() !void {
move(4, 1, 2, 3);
}
 
</syntaxhighlight>
 
=={{header|zkl}}==
{{trans|C}}
<langsyntaxhighlight lang="zkl">fcn move(n, from,to,via){
if (n>0){
move(n-1, from,via,to);
Line 5,036 ⟶ 7,884:
}
}
move(3, 1,2,3);</langsyntaxhighlight>
{{out}}
<pre>
3

edits