Towers of Hanoi: Difference between revisions

m
(→‎JS ES6: Updated function and output, tidied.)
(46 intermediate revisions by 24 users not shown)
Line 10:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F hanoi(ndisks, startPeg = 1, endPeg = 3) -> NVoid
I ndisks
hanoi(ndisks - 1, startPeg, 6 - startPeg - endPeg)
Line 16:
hanoi(ndisks - 1, 6 - startPeg - endPeg, endPeg)
 
hanoi(ndisks' 3)</langsyntaxhighlight>
 
{{out}}
Line 31:
=={{header|360 Assembly}}==
{{trans|PL/I}}
<langsyntaxhighlight lang="360asm">* Towers of Hanoi 08/09/2015
HANOITOW CSECT
USING HANOITOW,R12 r12 : base register
Line 102:
STACKLEN EQU *-STACKDS
YREGS
END HANOITOW</langsyntaxhighlight>
{{out}}
<pre style="height:18ex">
Line 121:
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}}==
 
<langsyntaxhighlight lang="8080asm"> org 100h
lhld 6 ; Top of CP/M usable memory
sphl ; Put the stack there
Line 165 ⟶ 322:
outstr: db 'Move disk from pole '
out1: db '* to pole '
out2: db '*',13,10,'$'</langsyntaxhighlight>
 
{{out}}
Line 188 ⟶ 345:
=={{header|8086 Assembly}}==
 
<langsyntaxhighlight lang="asm"> cpu 8086
bits 16
org 100h
Line 218 ⟶ 375:
outstr: db 'Move disk from pole '
out1: db '* to pole '
out2: db '*',13,10,'$'</langsyntaxhighlight>
 
{{out}}
Line 240 ⟶ 397:
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
5 var, disks
var sa
Line 261 ⟶ 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 272 ⟶ 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 289 ⟶ 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 300 ⟶ 527:
end
 
move(4, 1, 2, 3)</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
<langsyntaxhighlight lang="algol60">begin
procedure movedisk(n, f, t);
integer n, f, t;
Line 329 ⟶ 556:
dohanoi(4, 1, 2, 3);
outstring(1,"Towers of Hanoi puzzle completed!")
end</langsyntaxhighlight>
{{out}}
<pre>Move disk from 1 to 3
Line 350 ⟶ 577:
 
=={{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 360 ⟶ 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 375 ⟶ 602:
move(4, 1,2,3)
)
</syntaxhighlight>
</lang>
 
=={{header|ALGOL-M}}==
<langsyntaxhighlight lang="algolm">begin
procedure move(n, src, via, dest);
integer n;
Line 395 ⟶ 622:
 
move(4, "1", "2", "3");
end</langsyntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Line 414 ⟶ 641:
 
=={{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 424 ⟶ 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 437 ⟶ 689:
PROC main()
move(4, 1,2,3)
ENDPROC</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
#proto hanoi(_X_,_Y_,_Z_,_W_)
Line 456 ⟶ 708:
_hanoi({discos}minus(1), aux, inicio, fin))
back
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 480 ⟶ 732:
{{works with|Dyalog APL}}
 
<langsyntaxhighlight APLlang="apl">hanoi←{
move←{
n from to via←⍵
Line 489 ⟶ 741:
}
'⊂Move disk from pole ⊃,I1,⊂ to pole ⊃,I1'⎕FMT↑move ⍵
}</langsyntaxhighlight>
 
{{out}}
Line 511 ⟶ 763:
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">---------------------- TOWERS OF HANOI ---------------------
 
-- hanoi :: Int -> (String, String, String) -> [(String, String)]
Line 518 ⟶ 770:
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 525 ⟶ 779:
end |λ|
end script
go's |λ|(n, abc)
end hanoi
 
 
---------------------------- 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 --------------------
 
-- 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 555 ⟶ 818:
end if
end mReturn
 
 
-- map :: (a -> b) -> [a] -> [b]
Line 567 ⟶ 831:
end tell
end map
 
 
-- unlines :: [String] -> String
Line 575 ⟶ 840:
set my text item delimiters to dlm
str
end unlines</langsyntaxhighlight>
{{Out}}
<pre>left -> right
Line 589 ⟶ 854:
''(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.)''
 
<langsyntaxhighlight lang="applescript">on hanoi(n, source, target)
set t1 to tab & "tower 1: " & tab
set t2 to tab & "tower 2: " & tab
Line 652 ⟶ 917:
set sourceTower to 1
set destinationTower to 2
hanoi(numberOfDiscs, sourceTower, destinationTower)</langsyntaxhighlight>
 
{{Out}}
Line 690 ⟶ 955:
 
=={{header|ARM Assembly}}==
<syntaxhighlight lang="text">.text
.global _start
_start: mov r0,#4 @ 4 disks,
Line 733 ⟶ 998:
spole: .ascii "* to pole "
dpole: .ascii "*\n"
mlen = . - moves</langsyntaxhighlight>
 
{{out}}
Line 757 ⟶ 1,022:
{{trans|D}}
 
<langsyntaxhighlight lang="rebol">hanoi: function [n f dir via][
if n>0 [
hanoi n-1 f via dir
Line 765 ⟶ 1,030:
]
hanoi 3 'L 'M 'R</langsyntaxhighlight>
 
{{out}}
Line 778 ⟶ 1,043:
 
=={{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 791 ⟶ 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 804 ⟶ 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 831 ⟶ 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 839 ⟶ 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}}
{{works with|MSX_BASIC}}
<lang gwbasic>10 DIM N(1024), F(1024), T(1024), V(1024): REM STACK PER PARAMETER
<syntaxhighlight lang="gwbasic">10 DEPTH=4: REM SHOULD EQUAL NUMBER OF DISKS
20 SP = 0: REM STACK POINTER
20 DIM N(DEPTH), F(DEPTH), T(DEPTH), V(DEPTH): REM STACK PER PARAMETER
30 N(SP) = 4: REM START WITH 4 DISCS
4030 F(SP) = 10: REM ON PEG 1REM STACK POINTER
5040 TN(SP) = 24: REM MOVESTART TOWITH PEG4 2DISCS
6050 VF(SP) = 31: REM VIAON PEG 31
60 T(SP) = 2: REM MOVE TO PEG 2
70 GOSUB 100
70 V(SP) = 3: REM VIA PEG 3
80 END
80 GOSUB 100
90 REM MOVE SUBROUTINE
90 END
99 REM MOVE SUBROUTINE
100 IF N(SP) = 0 THEN RETURN
110 OS = SP: REM STORE STACK POINTER
Line 871 ⟶ 1,139:
240 GOSUB 100
250 SP = SP - 1 : REM RESTORE STACK POINTER FOR CALLER
260 RETURN</langsyntaxhighlight>
 
===Using binary method===
{{works with|Chipmunk Basic}}
{{works with|Commodore BASIC}}
Very fast version in BASIC V2 on Commodore C-64
{{works with|MSX_BASIC}}
<lang gwbasic> 10 def fnm(x)=x-int(x/3)*3:rem modulo
<syntaxhighlight lang="gwbasic"> 10 DEF FNM3(X)=X-INT(X/3)*3:REM MODULO 3
20 n=4:gosub 100
3020 endN=4:GOSUB 100
100 rem30 hanoiEND
110 :for99 m=1REM to 2^n-1HANOI
100 :FOR M=1 TO 2^N-1
120 ::print m;":",fnm(m and m-1)+1;" to ";fnm((m or m-1)+1)+1
110 ::PRINT MID$(STR$(M),2);":",FNM3(M AND M-1)+1;"TO";FNM3((M OR M-1)+1)+1
130 :next
130 :NEXT M
140 return</lang>
140 RETURN</syntaxhighlight>
{{out}}
<pre>1 : 1 toTO 3
2 : 1 toTO 2
3 : 3 toTO 2
4 : 1 toTO 3
5 : 2 toTO 1
6 : 2 toTO 3
7 : 1 toTO 3
8 : 1 toTO 2
9 : 3 toTO 2
10 : 3 toTO 1
11 : 2 toTO 1
12 : 3 toTO 2
13 : 1 toTO 3
14 : 1 toTO 2
15 : 3 toTO 2 </pre>
 
==={{header|BASIC256}}===
<langsyntaxhighlight BASIC256lang="basic256">call move(4,1,2,3)
print "Towers of Hanoi puzzle completed!"
end
Line 912 ⟶ 1,182:
call move(n-1, viaPeg, toPeg, fromPeg)
end if
end subroutine</langsyntaxhighlight>
 
{{out}}
Line 933 ⟶ 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 962 ⟶ 1,243:
call :move !x! %via% %to% %from%
)
exit /b 0</langsyntaxhighlight>
{{Out}}
<pre>Move top disk from pole START to pole HELPER.
Line 984 ⟶ 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 1,019 ⟶ 1,300:
Size%(peg%) = Size%(peg%)-1
PRINTTAB(13+26*(peg%-1)-disc%,20-Size%(peg%))STRING$(2*disc%+1," ");
ENDPROC</langsyntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let start() be move(4, 1, 2, 3)
Line 1,029 ⟶ 1,310:
writef("Move disk from pole %N to pole %N*N", src, dest);
move(n-1, via, src, dest)
$)</langsyntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Line 1,048 ⟶ 1,329:
 
=={{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 1,076 ⟶ 1,356:
'''Based on:''' [[APL]]
 
<langsyntaxhighlight lang="bqn">Move ← {
𝕩⊑⊸≤0 ? ⟨⟩;
𝕊 n‿from‿to‿via:
Line 1,083 ⟶ 1,363:
l∾(<from‿to)∾r
}
{"Move disk from pole "∾(•Fmt 𝕨)∾" to pole "∾•Fmt 𝕩}´˘>Move 4‿1‿2‿3</langsyntaxhighlight>
<syntaxhighlight lang="text">┌─
╵"Move disk from pole 1 to pole 3
Move disk from pole 1 to pole 2
Line 1,100 ⟶ 1,380:
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2"
┘</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( move
= n from to via
. !arg:(?n,?from,?to,?via)
Line 1,114 ⟶ 1,394:
)
& move$(4,1,2,3)
);</langsyntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 3
Line 1,134 ⟶ 1,414:
=={{header|Brainf***}}==
 
<langsyntaxhighlight lang="brainfuck">[
This implementation is recursive and uses
a stack, consisting of frames that are 8
Line 1,286 ⟶ 1,566:
>>[<<+>>-]<< step = next
<
]</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void move(int n, int from, int via, int to)
Line 1,305 ⟶ 1,585:
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 1,366 ⟶ 1,646:
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 1,377 ⟶ 1,657:
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 1,389 ⟶ 1,669:
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===
<langsyntaxhighlight lang="lisp">(defn towers-of-hanoi [n from to via]
(when (pos? n)
(towers-of-hanoi (dec n) from via to)
(printf "Move from %s to %s\n" from to)
(recur (dec n) via to from)))</langsyntaxhighlight>
===Lazy Solution===
<langsyntaxhighlight 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)))))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">move = proc (n, from, via, to: int)
po: stream := stream$primary_output()
if n > 0 then
Line 1,420 ⟶ 1,718:
start_up = proc ()
move(4, 1, 2, 3)
end start_up</langsyntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Line 1,441 ⟶ 1,739:
{{trans|C}}
{{works with|OpenCOBOL|2.0}}
<langsyntaxhighlight lang="cobol"> >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. towers-of-hanoi.
Line 1,468 ⟶ 1,766:
END-IF
.
END PROGRAM move-disk.</langsyntaxhighlight>
 
{{ Number of disks also }}
<langsyntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. towers-of-hanoi.
Line 1,501 ⟶ 1,799:
.
END PROGRAM move-disk.
</syntaxhighlight>
</lang>
 
=== ANSI-74 solution ===
Line 1,509 ⟶ 1,807:
{{works with|CIS COBOL|4.2}}{{works with|GnuCOBOL|3.0-rc1.0}}
 
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. ITERATIVE-TOWERS-OF-HANOI.
AUTHOR. SOREN ROUG.
Line 1,600 ⟶ 1,898:
MOVE FROM-POLE TO VIA-POLE.
MOVE TMP-P TO FROM-POLE.
</syntaxhighlight>
</lang>
 
=={{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 1,610 ⟶ 1,908:
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 1,619 ⟶ 1,917:
(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 1,635 ⟶ 1,933:
void main() {
hanoi(3, 'L', 'M', 'R');
}</langsyntaxhighlight>
{{out}}
<pre>Move disk 1 from L to M
Line 1,646 ⟶ 1,944:
===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 1,688 ⟶ 1,986:
'\n'.putchar;
}
}</langsyntaxhighlight>
{{out}}
<pre>| 3 2 1
Line 1,724 ⟶ 2,022:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">main() {
moveit(from,to) {
print("move ${from} ---> ${to}");
Line 1,738 ⟶ 2,036:
 
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,753 ⟶ 2,051:
 
hanoi(3, 3, 1, 2);
}</langsyntaxhighlight>
 
{{out}}
Line 1,851 ⟶ 2,149:
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc move(byte n, src, via, dest) void:
if n>0 then
move(n-1, src, dest, via);
Line 1,861 ⟶ 2,159:
proc nonrec main() void:
move(4, 1, 2, 3)
corp</langsyntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Line 1,883 ⟶ 2,181:
{{trans|Swift}}
 
<langsyntaxhighlight lang="dyalect">func hanoi(n, a, b, c) {
if n > 0 {
hanoi(n - 1, a, c, b)
Line 1,891 ⟶ 2,189:
}
hanoi(4, "A", "B", "C")</langsyntaxhighlight>
 
{{out}}
Line 1,912 ⟶ 2,210:
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def move(out, n, fromPeg, toPeg, viaPeg) {
if (n.aboveZero()) {
move(out, n.previous(), fromPeg, viaPeg, toPeg)
Line 1,920 ⟶ 2,218:
}
 
move(stdout, 4, def left {}, def right {}, def middle {})</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang>func hanoi n src dst aux . .
proc hanoi n src dst aux . .
if n >= 1
call hanoiif n ->= 1 src aux dst
print "Move "hanoi &n src- &1 " to "src &aux dst
call hanoi nprint -"Move 1" aux dst& 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. HereIn 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.
<langsyntaxhighlight lang="edsac">
[Towers of Hanoi task for Rosetta Code.]
[EDSAC program, Initial Orders 2.]
Line 2,092 ⟶ 2,392:
PF [acc = 0 on entry]
[end]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,106 ⟶ 2,406:
 
=={{header|Eiffel}}==
<langsyntaxhighlight Eiffellang="eiffel">class
APPLICATION
 
Line 2,133 ⟶ 2,433:
end
end
end</langsyntaxhighlight>
 
=={{header|Ela}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="ela">open monad io
:::IO
 
Line 2,153 ⟶ 2,453:
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 2,169 ⟶ 2,469:
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 2,185 ⟶ 2,485:
end
 
RC.hanoi(3)</langsyntaxhighlight>
 
{{out}}
Line 2,200 ⟶ 2,500:
=={{header|Emacs Lisp}}==
{{Trans|Common Lisp}}
<langsyntaxhighlight lang="lisp">(defun move (n from to via)
(if (= n 1)
(message "Move from %S to %S" from to)
(move (- n 1) from via to)
(message "Move from %S to %S" from to)
(move (- n 1) via to from)))</langsyntaxhighlight>
 
=={{header|EMal}}==
{{trans|C#}}
<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 2,272 ⟶ 2,597:
MOVE
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,295 ⟶ 2,620:
 
{{Works with| Office 365 Betas 2021}}
<langsyntaxhighlight lang="lisp">SHOWHANOI
=LAMBDA(n,
FILTERP(
Line 2,328 ⟶ 2,653:
)
)
)</langsyntaxhighlight>
 
And assuming that these generic lambdas are also bound to the following names in Name Manager:
 
<langsyntaxhighlight lang="lisp">APPEND
=LAMBDA(xs,
LAMBDA(ys,
Line 2,357 ⟶ 2,682:
FILTER(xs, p(xs))
)
)</langsyntaxhighlight>
 
In the output below, the expression in B2 defines an array of strings which additionally populate the following cells.
Line 2,405 ⟶ 2,730:
 
=={{header|Ezhil}}==
<syntaxhighlight lang="python">
<lang Python>
# (C) 2013 Ezhil Language Project
# Tower of Hanoi – recursive solution
Line 2,433 ⟶ 2,758:
 
ஹோனாய்(4,”அ”,”ஆ”,0)
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">#light
let rec hanoi num start finish =
match num with
Line 2,447 ⟶ 2,772:
(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|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel locals math ;
IN: rosettacode.hanoi
 
Line 2,460 ⟶ 2,785:
from to move
n 1 - other to from hanoi
] when ;</langsyntaxhighlight>
In the REPL:
<pre>( scratchpad ) 3 1 3 2 hanoi
Line 2,472 ⟶ 2,797:
 
=={{header|FALSE}}==
<langsyntaxhighlight 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;!%%%</langsyntaxhighlight>
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">Func Hanoi( n, f, t, v ) =
if n = 0 then
!'';
Line 2,485 ⟶ 2,810:
!f;!' -> ';!t;!', ';
Hanoi(n - 1, v, t, f)
fi.</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight FOCALlang="focal">01.10 S N=4;S S=1;S V=2;S T=3
01.20 D 2
01.30 Q
Line 2,505 ⟶ 2,830:
 
03.10 T %1,"MOVE DISK FROM POLE",S(D)
03.20 T " TO POLE",T(D),!</langsyntaxhighlight>
 
{{out}}
Line 2,527 ⟶ 2,852:
=={{header|Forth}}==
With locals:
<langsyntaxhighlight lang="forth">CREATE peg1 ," left "
CREATE peg2 ," middle "
CREATE peg3 ," right "
Line 2,539 ⟶ 2,864:
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 2,554 ⟶ 2,879:
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 2,576 ⟶ 2,901:
END SUBROUTINE Move
 
END PROGRAM TOWER</langsyntaxhighlight>
 
{{ More informative version }}
<langsyntaxhighlight lang="fortran">
PROGRAM TOWER2
Line 2,598 ⟶ 2,923:
END SUBROUTINE Move
END PROGRAM TOWER2 </langsyntaxhighlight>
 
=={{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 2,617 ⟶ 2,942:
move 4, 1, 2, 3
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,651 ⟶ 2,976:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
/** Set up the recursive call for n disks */
hanoi[n] := hanoi[n, 1, 3, 2]
Line 2,667 ⟶ 2,992:
 
hanoi[7]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1, @"Towers of Hanoi", ( 0, 0, 300, 300 )
<lang futurebasic>
window 1, @"Towers of Hanoi", ( 0, 0, 300, 300 )
 
void local fn Move( n as long, fromPeg as long, toPeg as long, viaPeg as long )
if n > 0
fn Move( n-1, fromPeg, viaPeg, toPeg )
print "Move disk from "; fromPeg; " to "; toPeg
fn Move( n-1, viaPeg, toPeg, fromPeg )
end if
end fn
 
Line 2,685 ⟶ 3,009:
print "Towers of Hanoi puzzle solved."
 
HandleEvents</syntaxhighlight>
</lang>
 
Output:
Line 2,711 ⟶ 3,034:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Tower_of_Hanoi}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. 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 storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Tower of Hanoi 01.png]]
In '''[https://formulae.org/?example=Tower_of_Hanoi this]''' page you can see the program(s) related to this task and their results.
 
'''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 2,747 ⟶ 3,100:
# B -> A
# B -> C
# A -> C</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,791 ⟶ 3,144:
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 2,809 ⟶ 3,162:
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 2,829 ⟶ 3,182:
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 2,844 ⟶ 3,197:
report()
check(STACK.A)
moveStack(STACK.A, STACK.C)</langsyntaxhighlight>
 
{{out}}
Line 2,915 ⟶ 3,268:
(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 2,937 ⟶ 3,290:
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:
<langsyntaxhighlight lang="haskell">-------------------------- HANOI -------------------------
 
hanoi ::
Line 2,969 ⟶ 3,322:
 
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</langsyntaxhighlight>
{{Out}}
<pre> left -> right
Line 3,005 ⟶ 3,358:
=={{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 3,013 ⟶ 3,366:
}
 
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 3,039 ⟶ 3,392:
}
return
end</langsyntaxhighlight>
 
=={{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 3,066 ⟶ 3,419:
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 3,077 ⟶ 3,430:
hanoi(n - 1, via , to , from)
)
)</langsyntaxhighlight>
 
=={{header|Ioke}}==
<langsyntaxhighlight lang="ioke"> = method(n, f, u, t,
if(n < 2,
"#{f} --> #{t}" println,
Line 3,092 ⟶ 3,445:
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 3,116 ⟶ 3,458:
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 3,125 ⟶ 3,467:
i.0 2
end.
)</langsyntaxhighlight>
The usage here is the same:
<pre> H1 2
Line 3,133 ⟶ 3,475:
;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 3,146 ⟶ 3,488:
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 3,157 ⟶ 3,499:
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 3,168 ⟶ 3,524:
}
}
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 3,188 ⟶ 3,544:
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===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 3,204 ⟶ 3,560:
// hanoi :: Int -> String -> String ->
// String -> [[String, String]]
const hanoi = n => (a, b, c) => {
const(a, gob, c) => hanoi(n - 1);{
const go = hanoi(n - 1);
 
return Boolean(n) ? [
...go(a, c, b),
...[
[a, b]
],
...go(c, b, a)
] : [];
};
 
return n ? [
...go(a, c, b),
...[
[a, b]
],
...go(c, b, a)
] : [];
};
 
// ---------------------- TEST -----------------------
Line 3,220 ⟶ 3,578:
.map(d => `${d[0]} -> ${d[1]}`)
.join("\n");
})();</langsyntaxhighlight>
{{Out}}
<pre>left -> right
Line 3,231 ⟶ 3,589:
 
=={{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 3,256 ⟶ 3,613:
 
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 3,266 ⟶ 3,623:
move(n-1; Via; To; From)
else empty
end;</langsyntaxhighlight>
'''Example''':
move(5; "A"; "B"; "C")
Line 3,272 ⟶ 3,629:
=={{header|Jsish}}==
From Javascript ES5 entry.
<langsyntaxhighlight lang="javascript">/* Towers of Hanoi, in Jsish */
 
function move(n, a, b, c) {
Line 3,302 ⟶ 3,659:
Move disk from B to C
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 3,310 ⟶ 3,667:
=={{header|Julia}}==
{{trans|R}}
<langsyntaxhighlight lang="julia">
function solve(n::Integer, from::Integer, to::Integer, via::Integer)
if n == 1
Line 3,322 ⟶ 3,679:
 
solve(4, 1, 2, 3)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,344 ⟶ 3,701:
 
=={{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 3,360 ⟶ 3,717:
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}}
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
:moveDisc %B !B %C !C %A !A %n !n { n A C B }
Line 3,383 ⟶ 3,740:
3 1 3 2 moveDisc
 
" " input</langsyntaxhighlight>
{{out}}
<pre>Move disc 1 from pole 1 to pole 3
Line 3,394 ⟶ 3,751:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
class Hanoi(disks: Int) {
Line 3,418 ⟶ 3,775:
Hanoi(3)
Hanoi(4)
}</langsyntaxhighlight>
 
{{out}}
Line 3,455 ⟶ 3,812:
</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 3,498 ⟶ 3,868:
}
 
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 3,510 ⟶ 3,880:
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 3,530 ⟶ 3,900:
=={{header|Liberty BASIC}}==
This looks much better with a GUI interface.
<langsyntaxhighlight lang="lb"> source$ ="A"
via$ ="B"
target$ ="C"
Line 3,548 ⟶ 3,918:
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 3,557 ⟶ 3,927:
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 3,565 ⟶ 3,935:
-- "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 3,574 ⟶ 3,944:
move :n-1 :via :to :from
end
move 4 "left "middle "right</langsyntaxhighlight>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">:- object(hanoi).
 
:- public(run/1).
Line 3,605 ⟶ 3,975:
nl.
 
:- end_object.</langsyntaxhighlight>
 
=={{header|LOLCODE}}==
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.2
HOW IZ I HANOI YR N AN YR SRC AN YR DST AN YR VIA
Line 3,627 ⟶ 3,997:
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 3,638 ⟶ 4,008:
end
 
move(4, 1, 2, 3)</langsyntaxhighlight>
 
{{More informative version }}
<syntaxhighlight lang="lua">
<lang Lua>
 
function move(n, src, via, dst)
Line 3,654 ⟶ 4,024:
move(4, 1, 2, 3)
 
</syntaxhighlight>
</lang>
 
===Hanoi Iterative===
<langsyntaxhighlight lang="lua">
#!/usr/bin/env luajit
local function printf(fmt, ...) io.write(string.format(fmt, ...)) end
Line 3,698 ⟶ 4,068:
 
hanoi(num)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,706 ⟶ 4,076:
 
===Hanoi Bitwise Fast===
<langsyntaxhighlight lang="lua">
#!/usr/bin/env luajit
-- binary solution
Line 3,721 ⟶ 4,091:
 
hanoi(num)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,732 ⟶ 4,102:
=={{header|M2000 Interpreter}}==
{{trans|FreeBasic}}
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Hanoi {
Rem HANOI TOWERS
Line 3,750 ⟶ 4,120:
}
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}}==
 
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
DIMENSION LIST(100)
SET LIST TO LIST
Line 3,793 ⟶ 4,217:
END OF PROGRAM
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,812 ⟶ 4,236:
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 3,828 ⟶ 4,251:
printf("Moving 2 disks from tower A to tower C using tower B.\n");
Hanoi(2,A,B,C);
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,841 ⟶ 4,264:
 
=={{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])</langsyntaxhighlight>
 
=={{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 3,852 ⟶ 4,275:
towerOfHanoi(n-1,B,C,A);
end
end</langsyntaxhighlight>
{{out|Sample output}}
<pre>towerOfHanoi(3,1,3,2)
Line 3,864 ⟶ 4,287:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">moveDisc = function(n, A, C, B)
if n == 0 then return
moveDisc n-1, A, B, C
Line 3,872 ⟶ 4,295:
 
// Move disc 3 from pole 1 to pole 3, with pole 2 as spare
moveDisc 3, 1, 3, 2</langsyntaxhighlight>
{{out}}
<pre>Move disc 1 from pole 1 to pole 3
Line 3,881 ⟶ 4,304:
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 3,896 ⟶ 4,350:
hanoi(3)
--><langsyntaxhighlight lang="mips">
# Towers of Hanoi
# MIPS assembly implementation (tested with MARS)
Line 3,998 ⟶ 4,452:
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 4,009 ⟶ 4,463:
ИП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 4,033 ⟶ 4,487:
 
ReadChar
END Towers.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Hanoi EXPORTS Main;
 
FROM IO IMPORT Put;
Line 4,052 ⟶ 4,506:
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 4,061 ⟶ 4,515:
move(n.previous(), viaPeg, toPeg, fromPeg)
 
move(3, "left", "right", "middle")</langsyntaxhighlight>
 
=={{header|MoonScript}}==
<langsyntaxhighlight lang="moonscript">hanoi = (n, src, dest, via) ->
if n > 1
hanoi n-1, src, via, dest
Line 4,071 ⟶ 4,525:
hanoi n-1, via, dest, src
 
hanoi 4,1,3,2</langsyntaxhighlight>
{{Out}}
<pre>1 -> 2
Line 4,089 ⟶ 4,543:
2 -> 3</pre>
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 4,108 ⟶ 4,562:
Hanoi(4)
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 4,117 ⟶ 4,571:
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 4,126 ⟶ 4,580:
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 4,138 ⟶ 4,592:
end
return moves
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,161 ⟶ 4,615:
 
=={{header|NewLISP}}==
<langsyntaxhighlight lang="lisp">(define (move n from to via)
(if (> n 0)
(move (- n 1) from via to
Line 4,167 ⟶ 4,621:
(move (- n 1) via to from))))
 
(move 4 1 2 3)</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight Pythonlang="python">proc hanoi(disks: int; fromTower, toTower, viaTower: string) =
if disks != 0:
hanoi(disks - 1, fromTower, viaTower, toTower)
Line 4,176 ⟶ 4,630:
hanoi(disks - 1, viaTower, toTower, fromTower)
hanoi(4, "1", "2", "3")</langsyntaxhighlight>
{{out}}
<pre>Move disk 1 from 1 to 3
Line 4,193 ⟶ 4,647:
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 4,210 ⟶ 4,712:
};
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Line 4,219 ⟶ 4,721:
 
The Interface - TowersOfHanoi.h:
<langsyntaxhighlight lang="objc">#import <Foundation/NSObject.h>
 
@interface TowersOfHanoi: NSObject {
Line 4,230 ⟶ 4,732:
-(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 4,252 ⟶ 4,754:
}
 
@end</langsyntaxhighlight>
Test code: TowersTest.m:
<langsyntaxhighlight lang="objc">#import <stdio.h>
#import "TowersOfHanoi.h"
 
Line 4,273 ⟶ 4,775:
}
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 4,284 ⟶ 4,786:
 
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 4,297 ⟶ 4,799:
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 4,308 ⟶ 4,810:
] ;
 
5 $left $middle $right) move </langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
proc {TowersOfHanoi N From To Via}
if N > 0 then
Line 4,320 ⟶ 4,822:
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 4,336 ⟶ 4,838:
}
\\ Testing n=3:
HanoiTowers(3,1,3);</langsyntaxhighlight>
 
{{Output}}
Line 4,353 ⟶ 4,855:
{{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 4,370 ⟶ 4,872:
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 4,396 ⟶ 4,898:
begin
MoveStack(4,tpLeft,tpCenter,tpRight);
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub hanoi {
my ($n, $from, $to, $via) = (@_, 1, 2, 3);
 
Line 4,409 ⟶ 4,911:
hanoi($n - 1, $via, $to, $from);
};
};</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<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>
Line 4,447 ⟶ 4,949:
<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>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre style="float:left">
Line 4,578 ⟶ 5,080:
{{trans|C}}
 
<langsyntaxhighlight lang="phl">module hanoi;
 
extern printf;
Line 4,593 ⟶ 5,095:
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 4,605 ⟶ 5,107:
move($n-1,$via,$to,$from);
}
}</langsyntaxhighlight>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">main =>
hanoi(3, left, center, right).
 
Line 4,616 ⟶ 5,118:
printf("Move disk %w from pole %w to pole %w\n", N, From, To),
hanoi(N - 1, Via, To, From).
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,630 ⟶ 5,132:
 
===Fast counting===
<langsyntaxhighlight Picatlang="picat">main =>
hanoi(64).
 
Line 4,644 ⟶ 5,146:
Count2 = move(N - 1, Via, To, From),
Count = Count1+Count2+1.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,651 ⟶ 5,153:
 
=={{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|PL/I}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="pli">tower: proc options (main);
 
call Move (4,1,2,3);
Line 4,677 ⟶ 5,179:
end Move;
 
end tower;</langsyntaxhighlight>
 
=={{header|PL/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 */
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}}==
 
<langsyntaxhighlight TeXlang="tex">\newcount\hanoidepth
\def\hanoi#1{%
\hanoidepth = #1
Line 4,699 ⟶ 5,249:
 
\hanoi{5}
\end</langsyntaxhighlight>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">define hanoi(n, src, dst, via);
if n > 0 then
hanoi(n - 1, src, via, dst);
Line 4,710 ⟶ 5,260:
enddefine;
 
hanoi(4, "left", "middle", "right");</langsyntaxhighlight>
 
=={{header|PostScript}}==
A million-page document, each page showing one move.
<langsyntaxhighlight PostScriptlang="postscript">%!PS-Adobe-3.0
%%BoundingBox: 0 0 300 300
 
Line 4,761 ⟶ 5,311:
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 4,777 ⟶ 5,327:
}
hanoi 3 "A" "B" "C"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 4,791 ⟶ 5,341:
=={{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 4,800 ⟶ 5,350:
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 4,821 ⟶ 5,371:
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 4,831 ⟶ 5,381:
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 4,846 ⟶ 5,396:
Hanoi(n,"Left Peg","Middle Peg","Right Peg")
PrintN(#CRLF$+"Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
{{out}}
Moving 3 pegs.
Line 4,862 ⟶ 5,412:
=={{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 4,879 ⟶ 5,429:
Or, separating the definition of the data from its display:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Towers of Hanoi'''
 
 
Line 4,906 ⟶ 5,456:
print(__doc__ + ':\n\n' + '\n'.join(
map(fromTo, hanoi(4)('left')('right')('mid'))
))</langsyntaxhighlight>
{{Out}}
<pre>Towers of Hanoi:
Line 4,930 ⟶ 5,480:
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 5,126 ⟶ 5,676:
# TEST ----------------------------------------------------
if __name__ == '__main__':
main()</langsyntaxhighlight>
<pre>Hanoi sequence for 3 disks:
 
Line 5,175 ⟶ 5,725:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ stack ] is rings ( --> [ )
 
[ rings share
Line 5,195 ⟶ 5,745:
 
say 'How to solve a three ring Towers of Hanoi puzzle:' cr cr
3 hanoi cr</langsyntaxhighlight>
 
{{out}}
Line 5,222 ⟶ 5,772:
'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 5,395 ⟶ 5,945:
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")
Line 5,409 ⟶ 5,959:
}
 
hanoimove(4, 1, 2, 3)</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define (hanoi n a b c)
Line 5,420 ⟶ 5,970:
(hanoi (- n 1) c b a)))
(hanoi 4 'left 'middle 'right)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>subset Peg of Int where 1|2|3;
 
multi hanoi (0, Peg $a, Peg $b, Peg $c) { }
Line 5,431 ⟶ 5,981:
say "Move $a to $b.";
hanoi $n - 1, $c, $b, $a;
}</langsyntaxhighlight>
 
=={{header|Rascal}}==
{{trans|Python}}
<langsyntaxhighlight lang="rascal">public void hanoi(ndisks, startPeg, endPeg){
if(ndisks>0){
hanoi(ndisks-1, startPeg, 6 - startPeg - endPeg);
Line 5,441 ⟶ 5,991:
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 5,459 ⟶ 6,009:
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 5,475 ⟶ 6,025:
# 4 disks
4 dohanoi
</syntaxhighlight>
</lang>
{{out}}
<pre>raven hanoi.rv
Line 5,496 ⟶ 6,046:
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Towers of Hanoi"
URL: http://rosettacode.org/wiki/Towers_of_Hanoi
Line 5,516 ⟶ 6,066:
]
 
hanoi 4</langsyntaxhighlight>
{{out}}
<pre>left -> right
Line 5,533 ⟶ 6,083:
left -> middle
right -> middle</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Move 4 1 2 3>;
};
 
Move {
0 e.X = ;
s.N s.Src s.Via s.Dest, <- s.N 1>: s.Next =
<Move s.Next s.Src s.Dest s.Via>
<Prout "Move disk from pole" s.Src "to pole" s.Dest>
<Move s.Next s.Via s.Src s.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|Retro}}==
<syntaxhighlight lang="retro">[[User:Wodan58|Wodan58]] ([[User talk:Wodan58|talk]])
<lang Retro>~~~
{ 'Num 'From 'To 'Via } [ var ] a:for-each
Line 5,548 ⟶ 6,127:
#3 #1 #3 #2 hanoi nl
[[User:Wodan58|Wodan58]] ([[User talk:Wodan58|talk]])</syntaxhighlight>
~~~</lang>
 
=={{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 5,570 ⟶ 6,149:
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 5,614 ⟶ 6,193:
 
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.*/
Line 5,675 ⟶ 6,254:
return /*it uses no variables, is uses BIFs instead*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
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 5,727 ⟶ 6,306:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
move(4, 1, 2, 3)
 
Line 5,734 ⟶ 6,313:
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 5,751 ⟶ 6,353:
n = 5
@towers = [[*1..n].reverse, [], []]
move(n)</langsyntaxhighlight>
 
{{out}}
Line 5,789 ⟶ 6,391:
 
===version 2===
<langsyntaxhighlight lang="ruby"># solve(source, via, target)
# Example:
# solve([5, 4, 3, 2, 1], [], [])
Line 5,817 ⟶ 6,419:
end
 
solve([5, 4, 3, 2, 1], [], [])</langsyntaxhighlight>
{{out}}
<pre>
Line 5,855 ⟶ 6,457:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">a = move(4, "1", "2", "3")
function move(n, a$, b$, c$)
if n > 0 then
Line 5,862 ⟶ 6,464:
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 5,881 ⟶ 6,483:
=={{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 5,891 ⟶ 6,493:
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 5,901 ⟶ 6,503:
‘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 5,920 ⟶ 6,522:
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 5,931 ⟶ 6,533:
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 5,968 ⟶ 6,570:
run[_2,Left,Right,Center]
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Recursive Process
<langsyntaxhighlight lang="scheme">(define (towers-of-hanoi n from to spare)
(define (print-move from to)
(display "Move[")
Line 5,986 ⟶ 6,588:
(towers-of-hanoi (- n 1) spare to from))))
 
(towers-of-hanoi 3 "A" "B" "C")</langsyntaxhighlight>
{{out}}
<pre>Move[A, B]
Line 5,998 ⟶ 6,600:
 
=={{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 6,005 ⟶ 6,607:
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 6,019 ⟶ 6,651:
}
 
hanoi(4);</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4">* # Note: count is global
 
define('hanoi(n,src,trg,tmp)') :(hanoi_end)
Line 6,034 ⟶ 6,666:
* # Test with 4 discs
hanoi(4,'A','C','B')
end</langsyntaxhighlight>
{{out}}
<pre>1: Move disc from A to B
Line 6,051 ⟶ 6,683:
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}}==
Line 6,058 ⟶ 6,723:
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">function hanoi(n, a, b, c) {
if (n>0) {
hanoi(n-1, a, c, b)
Line 6,074 ⟶ 6,739:
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 6,086 ⟶ 6,751:
}
 
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 6,097 ⟶ 6,762:
}
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 6,115 ⟶ 6,780:
}
 
hanoi 4</langsyntaxhighlight>
{{out}}
<pre>1: move from A to B
Line 6,135 ⟶ 6,800:
=={{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 6,216 ⟶ 6,881:
 
End
</syntaxhighlight>
</lang>
 
=={{header|Tiny BASIC}}==
Line 6,223 ⟶ 6,888:
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.
 
<langsyntaxhighlight lang="tinybasic"> 5 PRINT "How many disks?"
INPUT D
IF D < 1 THEN GOTO 5
Line 6,267 ⟶ 6,932:
LET Z = Z / 2
IF Z = 0 THEN RETURN
GOTO 55</langsyntaxhighlight>
 
{{out}}<pre>
Line 6,290 ⟶ 6,955:
 
=={{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 6,302 ⟶ 6,967:
n 1- sc sb sa recurse
] ifTrue
] is hanoi</langsyntaxhighlight>
 
 
=={{header|True BASIC}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="basic">
DECLARE SUB hanoi
 
Line 6,328 ⟶ 6,993:
PRINT "Pulsa un tecla para salir"
END
</syntaxhighlight>
</lang>
 
 
=={{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 6,356 ⟶ 7,021:
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 6,369 ⟶ 7,034:
Proc _Move (a@ - 1, d@, c@, b@)
EndIf
Return</langsyntaxhighlight>
 
=={{header|UNIX ShellUiua}}==
{{works with|bashUiua|0.10.0}}
<syntaxhighlight lang ="bash">#!/bin/bash
F ← |1.0 (
&p ⊏[1 2] &pf "Move disc [from to]: "
| 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}}==
move()
{{works with|Bourne Again SHell}}
{
{{works with|Korn Shell}}
local n="$1"
{{works with|Z Shell}}
local from="$2"
<syntaxhighlight lang="bash">function move {
local to="$3"
localtypeset via-i n="$4"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 6,401 ⟶ 7,124:
#show+
 
main = ^|T(~&,' -> '--)* move/4 <'start','end','middle'></langsyntaxhighlight>
{{out}}
<pre>start -> middle
Line 6,418 ⟶ 7,141:
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 6,431 ⟶ 7,199:
 
Move 4,1,2,3
WScript.StdOut.Write("Towers of Hanoi puzzle completed!")</langsyntaxhighlight>
 
{{out}}
Line 6,453 ⟶ 7,221:
=={{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 6,477 ⟶ 7,245:
Num_Pop(1,4)
}
Return</langsyntaxhighlight>
 
=={{header|Vim Script}}==
<langsyntaxhighlight lang="vimscript">function TowersOfHanoi(n, from, to, via)
if (a:n > 1)
call TowersOfHanoi(a:n-1, a:from, a:via, a:to)
Line 6,490 ⟶ 7,258:
endfunction
 
call TowersOfHanoi(4, 1, 3, 2)</langsyntaxhighlight>
 
{{Out}}
Line 6,510 ⟶ 7,278:
 
=={{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 6,522 ⟶ 7,290:
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.
<langsyntaxhighlight VTL2lang="vtl2">1000 N=4
1010 F=1
1020 T=2
Line 6,576 ⟶ 7,378:
5080 R=:S)
5090 S=S-1
5100 #=!</langsyntaxhighlight>
{{out}}
<pre>
Line 6,598 ⟶ 7,400:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">class Hanoi {
construct new(disks) {
_moves = 0
Line 6,617 ⟶ 7,419:
 
Hanoi.new(3)
Hanoi.new(4)</langsyntaxhighlight>
 
{{out}}
Line 6,653 ⟶ 7,455:
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 6,667 ⟶ 7,496:
];
 
MoveTower(3, "left", "right", "center")</langsyntaxhighlight>
 
{{out}}
Line 6,681 ⟶ 7,510:
 
=={{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 6,697 ⟶ 7,526:
local:hanoi(4, 1, 2, 3)
}
</hanoi></langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="xml"><?xml version="1.0" encoding="UTF-8"?>
<hanoi>
<move disk="1">
Line 6,761 ⟶ 7,590:
<to>2</to>
</move>
</hanoi></langsyntaxhighlight>
 
=={{header|XSLT}}==
<langsyntaxhighlight lang="xml"><xsl:template name="hanoi">
<xsl:param name="n"/>
<xsl:param name="from">left</xsl:param>
Line 6,789 ⟶ 7,618:
</xsl:call-template>
</xsl:if>
</xsl:template></langsyntaxhighlight>
 
<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 6,823 ⟶ 7,652:
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}}
<langsyntaxhighlight lang="zig">const std = @import("std");
 
pub fn print(from: u32, to: u32) void {
Line 6,847 ⟶ 7,826:
}
 
</syntaxhighlight>
</lang>
 
=={{header|zkl}}==
{{trans|C}}
<langsyntaxhighlight lang="zkl">fcn move(n, from,to,via){
if (n>0){
move(n-1, from,via,to);
Line 6,858 ⟶ 7,837:
}
}
move(3, 1,2,3);</langsyntaxhighlight>
{{out}}
<pre>
1,480

edits