Towers of Hanoi: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 10:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F hanoi(ndisks, startPeg = 1, endPeg = 3) -> N
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 127:
This should work on any Commodore 8-bit computer; just set `temp` to an appropriate zero-page location.
<langsyntaxhighlight 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
Line 260:
bne loop
done_print:
rts</langsyntaxhighlight>
 
{{Out}}
Line 281:
=={{header|8080 Assembly}}==
 
<langsyntaxhighlight lang="8080asm"> org 100h
lhld 6 ; Top of CP/M usable memory
sphl ; Put the stack there
Line 322:
outstr: db 'Move disk from pole '
out1: db '* to pole '
out2: db '*',13,10,'$'</langsyntaxhighlight>
 
{{out}}
Line 345:
=={{header|8086 Assembly}}==
 
<langsyntaxhighlight lang="asm"> cpu 8086
bits 16
org 100h
Line 375:
outstr: db 'Move disk from pole '
out1: db '* to pole '
out2: db '*',13,10,'$'</langsyntaxhighlight>
 
{{out}}
Line 397:
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
5 var, disks
var sa
Line 418:
disks @ 1 2 3 hanoi cr bye
 
</syntaxhighlight>
</lang>
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">public function move(n:int, from:int, to:int, via:int):void
{
if (n > 0)
Line 429:
move(n - 1, via, to, from);
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
 
procedure Towers is
Line 446:
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 457:
end
 
move(4, 1, 2, 3)</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
<langsyntaxhighlight lang="algol60">begin
procedure movedisk(n, f, t);
integer n, f, t;
Line 486:
dohanoi(4, 1, 2, 3);
outstring(1,"Towers of Hanoi puzzle completed!")
end</langsyntaxhighlight>
{{out}}
<pre>Move disk from 1 to 3
Line 507:
 
=={{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 517:
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 532:
move(4, 1,2,3)
)
</syntaxhighlight>
</lang>
 
=={{header|ALGOL-M}}==
<langsyntaxhighlight lang="algolm">begin
procedure move(n, src, via, dest);
integer n;
Line 552:
 
move(4, "1", "2", "3");
end</langsyntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Line 573:
===Recursive===
Following Agena, Algol 68, AmigaE...
<langsyntaxhighlight lang="pascal">begin
procedure move ( integer value n, from, to, via ) ;
if n > 0 then begin
Line 582:
move( 4, 1, 2, 3 )
end.</langsyntaxhighlight>
 
===Iterative===
{{Trans|Tiny BASIC}}
<langsyntaxhighlight lang="pascal">begin % iterative towers of hanoi - translated from Tiny Basic %
integer d, n;
while begin writeon( "How many disks? " );
Line 606:
write( i_w := 1, s_w := 0, "Move disc on peg ", s + 1, " to peg ", t + 1 )
end
end.</langsyntaxhighlight>
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">PROC move(n, from, to, via)
IF n > 0
move(n-1, from, via, to)
Line 619:
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 638:
_hanoi({discos}minus(1), aux, inicio, fin))
back
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 662:
{{works with|Dyalog APL}}
 
<langsyntaxhighlight APLlang="apl">hanoi←{
move←{
n from to via←⍵
Line 671:
}
'⊂Move disk from pole ⊃,I1,⊂ to pole ⊃,I1'⎕FMT↑move ⍵
}</langsyntaxhighlight>
 
{{out}}
Line 693:
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">--------------------- TOWERS OF HANOI --------------------
 
-- hanoi :: Int -> (String, String, String) -> [(String, String)]
Line 770:
set my text item delimiters to dlm
str
end unlines</langsyntaxhighlight>
{{Out}}
<pre>left -> right
Line 784:
''(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 847:
set sourceTower to 1
set destinationTower to 2
hanoi(numberOfDiscs, sourceTower, destinationTower)</langsyntaxhighlight>
 
{{Out}}
Line 885:
 
=={{header|ARM Assembly}}==
<syntaxhighlight lang="text">.text
.global _start
_start: mov r0,#4 @ 4 disks,
Line 928:
spole: .ascii "* to pole "
dpole: .ascii "*\n"
mlen = . - moves</langsyntaxhighlight>
 
{{out}}
Line 952:
{{trans|D}}
 
<langsyntaxhighlight lang="rebol">hanoi: function [n f dir via][
if n>0 [
hanoi n-1 f via dir
Line 960:
]
hanoi 3 'L 'M 'R</langsyntaxhighlight>
 
{{out}}
Line 973:
 
=={{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 986:
}
}
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 999:
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 1,026:
{{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 1,034:
END SUB
 
move 4,1,2,3</langsyntaxhighlight>
 
===Using <code>GOSUB</code>s===
Line 1,041:
{{works with|Commodore BASIC}}
{{works with|GW-BASIC}}
<langsyntaxhighlight lang="gwbasic">10 DEPTH=4: REM SHOULD EQUAL NUMBER OF DISKS
20 DIM N(DEPTH), F(DEPTH), T(DEPTH), V(DEPTH): REM STACK PER PARAMETER
30 SP = 0: REM STACK POINTER
Line 1,067:
240 GOSUB 100
250 SP = SP - 1 : REM RESTORE STACK POINTER FOR CALLER
260 RETURN</langsyntaxhighlight>
 
===Using binary method===
{{works with|Commodore BASIC}}
Very fast version in BASIC V2 on Commodore C-64
<langsyntaxhighlight lang="gwbasic"> 10 DEF FNM3(X)=X-INT(X/3)*3:REM MODULO 3
20 N=4:GOSUB 100
30 END
Line 1,079:
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</langsyntaxhighlight>
{{out}}
<pre>1: 1 TO 3
Line 1,098:
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256">call move(4,1,2,3)
print "Towers of Hanoi puzzle completed!"
end
Line 1,108:
call move(n-1, viaPeg, toPeg, fromPeg)
end if
end subroutine</langsyntaxhighlight>
 
{{out}}
Line 1,131:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 1,158:
call :move !x! %via% %to% %from%
)
exit /b 0</langsyntaxhighlight>
{{Out}}
<pre>Move top disk from pole START to pole HELPER.
Line 1,180:
=={{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,215:
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,225:
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,247:
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,272:
'''Based on:''' [[APL]]
 
<langsyntaxhighlight lang="bqn">Move ← {
𝕩⊑⊸≤0 ? ⟨⟩;
𝕊 n‿from‿to‿via:
Line 1,279:
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,296:
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,310:
)
& move$(4,1,2,3)
);</langsyntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 3
Line 1,330:
=={{header|Brainf***}}==
 
<langsyntaxhighlight lang="brainfuck">[
This implementation is recursive and uses
a stack, consisting of frames that are 8
Line 1,482:
>>[<<+>>-]<< step = next
<
]</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void move(int n, int from, int via, int to)
Line 1,501:
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,562:
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,573:
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,585:
move(n - 1, via, to, from);
}
}</langsyntaxhighlight>
 
=={{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,616:
start_up = proc ()
move(4, 1, 2, 3)
end start_up</langsyntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Line 1,637:
{{trans|C}}
{{works with|OpenCOBOL|2.0}}
<langsyntaxhighlight lang="cobol"> >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. towers-of-hanoi.
Line 1,664:
END-IF
.
END PROGRAM move-disk.</langsyntaxhighlight>
 
{{ Number of disks also }}
<langsyntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. towers-of-hanoi.
Line 1,697:
.
END PROGRAM move-disk.
</syntaxhighlight>
</lang>
 
=== ANSI-74 solution ===
Line 1,705:
{{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,796:
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,806:
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,815:
(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,831:
void main() {
hanoi(3, 'L', 'M', 'R');
}</langsyntaxhighlight>
{{out}}
<pre>Move disk 1 from L to M
Line 1,842:
===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,884:
'\n'.putchar;
}
}</langsyntaxhighlight>
{{out}}
<pre>| 3 2 1
Line 1,920:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">main() {
moveit(from,to) {
print("move ${from} ---> ${to}");
Line 1,934:
 
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,949:
 
hanoi(3, 3, 1, 2);
}</langsyntaxhighlight>
 
{{out}}
Line 2,047:
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc move(byte n, src, via, dest) void:
if n>0 then
move(n-1, src, dest, via);
Line 2,057:
proc nonrec main() void:
move(4, 1, 2, 3)
corp</langsyntaxhighlight>
{{out}}
<pre>Move disk from pole 1 to pole 2
Line 2,079:
{{trans|Swift}}
 
<langsyntaxhighlight lang="dyalect">func hanoi(n, a, b, c) {
if n > 0 {
hanoi(n - 1, a, c, b)
Line 2,087:
}
hanoi(4, "A", "B", "C")</langsyntaxhighlight>
 
{{out}}
Line 2,108:
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def move(out, n, fromPeg, toPeg, viaPeg) {
if (n.aboveZero()) {
move(out, n.previous(), fromPeg, viaPeg, toPeg)
Line 2,116:
}
 
move(stdout, 4, def left {}, def right {}, def middle {})</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">func hanoi n src dst aux . .
if n >= 1
call hanoi n - 1 src aux dst
Line 2,127:
.
.
call hanoi 5 1 2 3</langsyntaxhighlight>
 
=={{header|EDSAC order code}}==
Line 2,133:
 
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,288:
PF [acc = 0 on entry]
[end]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,302:
 
=={{header|Eiffel}}==
<langsyntaxhighlight Eiffellang="eiffel">class
APPLICATION
 
Line 2,329:
end
end
end</langsyntaxhighlight>
 
=={{header|Ela}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="ela">open monad io
:::IO
 
Line 2,349:
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,365:
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,381:
end
 
RC.hanoi(3)</langsyntaxhighlight>
 
{{out}}
Line 2,396:
=={{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|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,468:
MOVE
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,491:
 
{{Works with| Office 365 Betas 2021}}
<langsyntaxhighlight lang="lisp">SHOWHANOI
=LAMBDA(n,
FILTERP(
Line 2,524:
)
)
)</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,553:
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,601:
 
=={{header|Ezhil}}==
<syntaxhighlight lang="python">
<lang Python>
# (C) 2013 Ezhil Language Project
# Tower of Hanoi – recursive solution
Line 2,629:
 
ஹோனாய்(4,”அ”,”ஆ”,0)
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">#light
let rec hanoi num start finish =
match num with
Line 2,643:
(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,656:
from to move
n 1 - other to from hanoi
] when ;</langsyntaxhighlight>
In the REPL:
<pre>( scratchpad ) 3 1 3 2 hanoi
Line 2,668:
 
=={{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,681:
!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,701:
 
03.10 T %1,"MOVE DISK FROM POLE",S(D)
03.20 T " TO POLE",T(D),!</langsyntaxhighlight>
 
{{out}}
Line 2,723:
=={{header|Forth}}==
With locals:
<langsyntaxhighlight lang="forth">CREATE peg1 ," left "
CREATE peg2 ," middle "
CREATE peg3 ," right "
Line 2,735:
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,750:
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,772:
END SUBROUTINE Move
 
END PROGRAM TOWER</langsyntaxhighlight>
 
{{ More informative version }}
<langsyntaxhighlight lang="fortran">
PROGRAM TOWER2
Line 2,794:
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,813:
move 4, 1, 2, 3
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,847:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
/** Set up the recursive call for n disks */
hanoi[n] := hanoi[n, 1, 3, 2]
Line 2,863:
 
hanoi[7]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<langsyntaxhighlight 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 )
Line 2,880:
print "Towers of Hanoi puzzle solved."
 
HandleEvents</langsyntaxhighlight>
 
Output:
Line 2,912:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">Hanoi := function(n)
local move;
move := function(n, a, b, c) # from, through, to
Line 2,941:
# B -> A
# B -> C
# A -> C</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,985:
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 3,003:
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 3,023:
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 3,038:
report()
check(STACK.A)
moveStack(STACK.A, STACK.C)</langsyntaxhighlight>
 
{{out}}
Line 3,109:
(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 3,131:
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 3,163:
 
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</langsyntaxhighlight>
{{Out}}
<pre> left -> right
Line 3,199:
=={{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,207:
}
 
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,233:
}
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,260:
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,271:
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,286:
hanoi = method(n,
H(n, 1, 2, 3)
)</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Hanoi.bas"
110 CALL HANOI(4,1,3,2)
120 DEF HANOI(DISK,FRO,TO,WITH)
Line 3,297:
160 CALL HANOI(DISK-1,WITH,TO,FRO)
170 END IF
180 END DEF</langsyntaxhighlight>
 
=={{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,310:
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,319:
i.0 2
end.
)</langsyntaxhighlight>
The usage here is the same:
<pre> H1 2
Line 3,327:
;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,340:
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,351:
move(n - 1, via, to, from);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">function move(n, a, b, c) {
if (n > 0) {
move(n-1, a, c, b);
Line 3,362:
}
}
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,382:
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,416:
.map(d => `${d[0]} -> ${d[1]}`)
.join("\n");
})();</langsyntaxhighlight>
{{Out}}
<pre>left -> right
Line 3,427:
 
=={{header|Joy}}==
<syntaxhighlight lang=Joy"joy">DEFINE hanoi == [[rolldown] infra] dip
[[[null] [pop pop] ]
[[dup2 [[rotate] infra] dip pred]
Line 3,435:
condnestrec.</syntaxhighlight>
Using it (5 is the number of disks.)
<syntaxhighlight lang=Joy"joy">[source destination temp] 5 hanoi.</syntaxhighlight>
 
=={{header|jq}}==
Line 3,451:
 
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,461:
move(n-1; Via; To; From)
else empty
end;</langsyntaxhighlight>
'''Example''':
move(5; "A"; "B"; "C")
Line 3,467:
=={{header|Jsish}}==
From Javascript ES5 entry.
<langsyntaxhighlight lang="javascript">/* Towers of Hanoi, in Jsish */
 
function move(n, a, b, c) {
Line 3,497:
Move disk from B to C
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 3,505:
=={{header|Julia}}==
{{trans|R}}
<langsyntaxhighlight lang="julia">
function solve(n::Integer, from::Integer, to::Integer, via::Integer)
if n == 1
Line 3,517:
 
solve(4, 1, 2, 3)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,539:
 
=={{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,555:
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,578:
3 1 3 2 moveDisc
 
" " input</langsyntaxhighlight>
{{out}}
<pre>Move disc 1 from pole 1 to pole 3
Line 3,589:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
class Hanoi(disks: Int) {
Line 3,613:
Hanoi(3)
Hanoi(4)
}</langsyntaxhighlight>
 
{{out}}
Line 3,652:
=={{header|lambdatalk}}==
(Following NewLisp, PicoLisp, Racket, Scheme)
<langsyntaxhighlight lang="scheme">
{def move
{lambda {:n :from :to :via}
Line 3,677:
> move disk 2 from A to B
> move disk 1 from C to B
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
 
define towermove(
Line 3,693:
}
 
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,705:
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,725:
=={{header|Liberty BASIC}}==
This looks much better with a GUI interface.
<langsyntaxhighlight lang="lb"> source$ ="A"
via$ ="B"
target$ ="C"
Line 3,743:
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,752:
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,760:
-- "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,769:
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,800:
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,822:
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,833:
end
 
move(4, 1, 2, 3)</langsyntaxhighlight>
 
{{More informative version }}
<syntaxhighlight lang="lua">
<lang Lua>
 
function move(n, src, via, dst)
Line 3,849:
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,893:
 
hanoi(num)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,901:
 
===Hanoi Bitwise Fast===
<langsyntaxhighlight lang="lua">
#!/usr/bin/env luajit
-- binary solution
Line 3,916:
 
hanoi(num)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,927:
=={{header|M2000 Interpreter}}==
{{trans|FreeBasic}}
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Hanoi {
Rem HANOI TOWERS
Line 3,945:
}
Hanoi
</syntaxhighlight>
</lang>
{{out}}
same as in FreeBasic
Line 3,951:
=={{header|MAD}}==
 
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
DIMENSION LIST(100)
SET LIST TO LIST
Line 3,988:
END OF PROGRAM
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,010:
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
Hanoi := proc(n::posint,a,b,c)
if n = 1 then
Line 4,023:
printf("Moving 2 disks from tower A to tower C using tower B.\n");
Hanoi(2,A,B,C);
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,036:
 
=={{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 4,047:
towerOfHanoi(n-1,B,C,A);
end
end</langsyntaxhighlight>
{{out|Sample output}}
<pre>towerOfHanoi(3,1,3,2)
Line 4,059:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">moveDisc = function(n, A, C, B)
if n == 0 then return
moveDisc n-1, A, B, C
Line 4,067:
 
// 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 4,091:
hanoi(3)
--><langsyntaxhighlight lang="mips">
# Towers of Hanoi
# MIPS assembly implementation (tested with MARS)
Line 4,193:
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,204:
ИП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,228:
 
ReadChar
END Towers.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Hanoi EXPORTS Main;
 
FROM IO IMPORT Put;
Line 4,247:
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,256:
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,266:
hanoi n-1, via, dest, src
 
hanoi 4,1,3,2</langsyntaxhighlight>
{{Out}}
<pre>1 -> 2
Line 4,284:
2 -> 3</pre>
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 4,303:
Hanoi(4)
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 4,333:
end
return moves
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,356:
 
=={{header|NewLISP}}==
<langsyntaxhighlight lang="lisp">(define (move n from to via)
(if (> n 0)
(move (- n 1) from via to
Line 4,362:
(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,371:
hanoi(disks - 1, viaTower, toTower, fromTower)
hanoi(4, "1", "2", "3")</langsyntaxhighlight>
{{out}}
<pre>Move disk 1 from 1 to 3
Line 4,390:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class Hanoi {
function : Main(args : String[]) ~ Nil {
Move(4, 1, 2, 3);
Line 4,405:
};
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Line 4,414:
 
The Interface - TowersOfHanoi.h:
<langsyntaxhighlight lang="objc">#import <Foundation/NSObject.h>
 
@interface TowersOfHanoi: NSObject {
Line 4,425:
-(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,447:
}
 
@end</langsyntaxhighlight>
Test code: TowersTest.m:
<langsyntaxhighlight lang="objc">#import <stdio.h>
#import "TowersOfHanoi.h"
 
Line 4,468:
}
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,479:
 
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,492:
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,503:
] ;
 
5 $left $middle $right) move </langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
proc {TowersOfHanoi N From To Via}
if N > 0 then
Line 4,515:
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,531:
}
\\ Testing n=3:
HanoiTowers(3,1,3);</langsyntaxhighlight>
 
{{Output}}
Line 4,548:
{{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,565:
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,591:
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,604:
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,642:
<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,773:
{{trans|C}}
 
<langsyntaxhighlight lang="phl">module hanoi;
 
extern printf;
Line 4,788:
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,800:
move($n-1,$via,$to,$from);
}
}</langsyntaxhighlight>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">main =>
hanoi(3, left, center, right).
 
Line 4,811:
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,825:
 
===Fast counting===
<langsyntaxhighlight Picatlang="picat">main =>
hanoi(64).
 
Line 4,839:
Count2 = move(N - 1, Via, To, From),
Count = Count1+Count2+1.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,846:
 
=={{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,872:
end Move;
 
end tower;</langsyntaxhighlight>
 
=={{header|PL/M}}==
Line 4,878:
Iterative solution as PL/M doesn't do recursion.
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
<langsyntaxhighlight lang="pli">100H: /* ITERATIVE TOWERS OF HANOI; TRANSLATED FROM TINY BASIC (VIA ALGOL W) */
 
/* CP/M BDOS SYSTEM CALL */
Line 4,902:
CALL PR$STRING( .( 0DH, 0AH, '$' ) );
END;
EOF</langsyntaxhighlight>
{{out}}
<pre>
Line 4,924:
=={{header|PlainTeX}}==
 
<langsyntaxhighlight TeXlang="tex">\newcount\hanoidepth
\def\hanoi#1{%
\hanoidepth = #1
Line 4,942:
 
\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,953:
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 5,004:
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 5,020:
}
hanoi 3 "A" "B" "C"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 5,034:
=={{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 5,043:
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 5,064:
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 5,074:
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 5,089:
Hanoi(n,"Left Peg","Middle Peg","Right Peg")
PrintN(#CRLF$+"Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
{{out}}
Moving 3 pegs.
Line 5,105:
=={{header|Python}}==
===Recursive===
<langsyntaxhighlight lang="python">def hanoi(ndisks, startPeg=1, endPeg=3):
if ndisks:
hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
Line 5,111:
hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)
hanoi(4)</langsyntaxhighlight>
{{out}} for ndisks=2
<pre>
Line 5,122:
Or, separating the definition of the data from its display:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Towers of Hanoi'''
 
 
Line 5,149:
print(__doc__ + ':\n\n' + '\n'.join(
map(fromTo, hanoi(4)('left')('right')('mid'))
))</langsyntaxhighlight>
{{Out}}
<pre>Towers of Hanoi:
Line 5,173:
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,369:
# TEST ----------------------------------------------------
if __name__ == '__main__':
main()</langsyntaxhighlight>
<pre>Hanoi sequence for 3 disks:
 
Line 5,418:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ stack ] is rings ( --> [ )
 
[ rings share
Line 5,438:
 
say 'How to solve a three ring Towers of Hanoi puzzle:' cr cr
3 hanoi cr</langsyntaxhighlight>
 
{{out}}
Line 5,465:
'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,638:
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,652:
}
 
hanoimove(4, 1, 2, 3)</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define (hanoi n a b c)
Line 5,663:
(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,674:
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,684:
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,702:
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,718:
# 4 disks
4 dohanoi
</syntaxhighlight>
</lang>
{{out}}
<pre>raven hanoi.rv
Line 5,739:
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Towers of Hanoi"
URL: http://rosettacode.org/wiki/Towers_of_Hanoi
Line 5,759:
]
 
hanoi 4</langsyntaxhighlight>
{{out}}
<pre>left -> right
Line 5,778:
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">[[User:Wodan58|Wodan58]] ([[User talk:Wodan58|talk]])
{ 'Num 'From 'To 'Via } [ var ] a:for-each
Line 5,791:
#3 #1 #3 #2 hanoi nl
[[User:Wodan58|Wodan58]] ([[User talk:Wodan58|talk]])</langsyntaxhighlight>
 
=={{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,813:
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,857:
 
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,918:
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,970:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
move(4, 1, 2, 3)
 
Line 5,977:
see "" + src + " to " + dst + nl
move(n - 1, via, dst, src) ok
</syntaxhighlight>
</lang>
 
=={{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,994:
n = 5
@towers = [[*1..n].reverse, [], []]
move(n)</langsyntaxhighlight>
 
{{out}}
Line 6,032:
 
===version 2===
<langsyntaxhighlight lang="ruby"># solve(source, via, target)
# Example:
# solve([5, 4, 3, 2, 1], [], [])
Line 6,060:
end
 
solve([5, 4, 3, 2, 1], [], [])</langsyntaxhighlight>
{{out}}
<pre>
Line 6,098:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">a = move(4, "1", "2", "3")
function move(n, a$, b$, c$)
if n > 0 then
Line 6,105:
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 6,124:
=={{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 6,134:
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 6,144:
‘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 6,163:
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 6,174:
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 6,211:
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 6,229:
(towers-of-hanoi (- n 1) spare to from))))
 
(towers-of-hanoi 3 "A" "B" "C")</langsyntaxhighlight>
{{out}}
<pre>Move[A, B]
Line 6,241:
 
=={{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,248:
hanoi(pred(disk), via, dest, source);
end if;
end func;</langsyntaxhighlight>
 
=={{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,262:
}
 
hanoi(4);</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4">* # Note: count is global
 
define('hanoi(n,src,trg,tmp)') :(hanoi_end)
Line 6,277:
* # Test with 4 discs
hanoi(4,'A','C','B')
end</langsyntaxhighlight>
{{out}}
<pre>1: Move disc from A to B
Line 6,301:
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">function hanoi(n, a, b, c) {
if (n>0) {
hanoi(n-1, a, c, b)
Line 6,317:
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,329:
}
 
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,340:
}
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,358:
}
 
hanoi 4</langsyntaxhighlight>
{{out}}
<pre>1: move from A to B
Line 6,378:
=={{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,459:
 
End
</syntaxhighlight>
</lang>
 
=={{header|Tiny BASIC}}==
Line 6,466:
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,510:
LET Z = Z / 2
IF Z = 0 THEN RETURN
GOTO 55</langsyntaxhighlight>
 
{{out}}<pre>
Line 6,533:
 
=={{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,545:
n 1- sc sb sa recurse
] ifTrue
] is hanoi</langsyntaxhighlight>
 
 
=={{header|True BASIC}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="basic">
DECLARE SUB hanoi
 
Line 6,571:
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,599:
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,612:
Proc _Move (a@ - 1, d@, c@, b@)
EndIf
Return</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 6,618:
{{works with|Korn Shell}}
{{works with|Z Shell}}
<langsyntaxhighlight lang="bash">function move {
typeset -i n=$1
typeset from=$2
Line 6,631:
}
move "$@"</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}}
<langsyntaxhighlight lang="bash">#!/bin/sh
if [ "$1" -gt 0 ]; then
"$0" "`expr $1 - 1`" "$2" "$4" "$3"
Line 6,642:
"$0" "`expr $1 - 1`" "$4" "$3" "$2"
fi
</syntaxhighlight>
</lang>
 
Output from any of the above:
Line 6,664:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import nat
 
move = ~&al^& ^rlPlrrPCT/~&arhthPX ^|W/~& ^|G/predecessor ^/~&htxPC ~&zyxPC
Line 6,670:
#show+
 
main = ^|T(~&,' -> '--)* move/4 <'start','end','middle'></langsyntaxhighlight>
{{out}}
<pre>start -> middle
Line 6,690:
=={{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,700:
 
Move 4,1,2,3
WScript.StdOut.Write("Towers of Hanoi puzzle completed!")</langsyntaxhighlight>
 
{{out}}
Line 6,722:
=={{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,746:
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,759:
endfunction
 
call TowersOfHanoi(4, 1, 3, 2)</langsyntaxhighlight>
 
{{Out}}
Line 6,779:
 
=={{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,791:
MoveTowerDisks(4, 1, 2, 3)
End Sub
End Module</langsyntaxhighlight>
 
=={{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,845:
5080 R=:S)
5090 S=S-1
5100 #=!</langsyntaxhighlight>
{{out}}
<pre>
Line 6,867:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="ecmascript">class Hanoi {
construct new(disks) {
_moves = 0
Line 6,886:
 
Hanoi.new(3)
Hanoi.new(4)</langsyntaxhighlight>
 
{{out}}
Line 6,924:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Text=12;
 
proc MoveTower(Discs, From, To, Using);
Line 6,936:
];
 
MoveTower(3, "left", "right", "center")</langsyntaxhighlight>
 
{{out}}
Line 6,950:
 
=={{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,966:
local:hanoi(4, 1, 2, 3)
}
</hanoi></langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="xml"><?xml version="1.0" encoding="UTF-8"?>
<hanoi>
<move disk="1">
Line 7,030:
<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 7,058:
</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 7,092:
print "Hanoi 2 ellapsed ... ";
hanoi2(22, 1, 3, 2)
print peek("millisrunning") - t2, " ms"</langsyntaxhighlight>
 
=={{header|Zig}}==
{{trans|C}}
<langsyntaxhighlight lang="zig">const std = @import("std");
 
pub fn print(from: u32, to: u32) void {
Line 7,116:
}
 
</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 7,127:
}
}
move(3, 1,2,3);</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits