Towers of Hanoi: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Joy}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 10:
{{trans|Python}}
<
I ndisks
hanoi(ndisks - 1, startPeg, 6 - startPeg - endPeg)
Line 16:
hanoi(ndisks - 1, 6 - startPeg - endPeg, endPeg)
hanoi(ndisks' 3)</
{{out}}
Line 31:
=={{header|360 Assembly}}==
{{trans|PL/I}}
<
HANOITOW CSECT
USING HANOITOW,R12 r12 : base register
Line 102:
STACKLEN EQU *-STACKDS
YREGS
END HANOITOW</
{{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.
<
; kernal print-char routine
Line 260:
bne loop
done_print:
rts</
{{Out}}
Line 281:
=={{header|8080 Assembly}}==
<
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,'$'</
{{out}}
Line 345:
=={{header|8086 Assembly}}==
<
bits 16
org 100h
Line 375:
outstr: db 'Move disk from pole '
out1: db '* to pole '
out2: db '*',13,10,'$'</
{{out}}
Line 397:
=={{header|8th}}==
<
5 var, disks
var sa
Line 418:
disks @ 1 2 3 hanoi cr bye
</syntaxhighlight>
=={{header|ActionScript}}==
<
{
if (n > 0)
Line 429:
move(n - 1, via, to, from);
}
}</
=={{header|Ada}}==
<
procedure Towers is
Line 446:
begin
Hanoi(4);
end Towers;</
=={{header|Agena}}==
<
if n > 0 then
move(n - 1, src, via, dst)
Line 457:
end
move(4, 1, 2, 3)</
=={{header|ALGOL 60}}==
<
procedure movedisk(n, f, t);
integer n, f, t;
Line 486:
dohanoi(4, 1, 2, 3);
outstring(1,"Towers of Hanoi puzzle completed!")
end</
{{out}}
<pre>Move disk from 1 to 3
Line 507:
=={{header|ALGOL 68}}==
<
IF n > 0 THEN
move(n - 1, from, via, to);
Line 517:
main: (
move(4, 1,2,3)
)</
COMMENT Disk number is also printed in this code (works with a68g): COMMENT
<
PROC move = (INT n, from, to, via) VOID:
IF n > 0 THEN
Line 532:
move(4, 1,2,3)
)
</syntaxhighlight>
=={{header|ALGOL-M}}==
<
procedure move(n, src, via, dest);
integer n;
Line 552:
move(4, "1", "2", "3");
end</
{{out}}
<pre>Move disk from pole 1 to pole 2
Line 573:
===Recursive===
Following Agena, Algol 68, AmigaE...
<
procedure move ( integer value n, from, to, via ) ;
if n > 0 then begin
Line 582:
move( 4, 1, 2, 3 )
end.</
===Iterative===
{{Trans|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.</
=={{header|AmigaE}}==
<
IF n > 0
move(n-1, from, via, to)
Line 619:
PROC main()
move(4, 1,2,3)
ENDPROC</
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
#proto hanoi(_X_,_Y_,_Z_,_W_)
Line 638:
_hanoi({discos}minus(1), aux, inicio, fin))
back
</syntaxhighlight>
{{out}}
<pre>
Line 662:
{{works with|Dyalog APL}}
<
move←{
n from to via←⍵
Line 671:
}
'⊂Move disk from pole ⊃,I1,⊂ to pole ⊃,I1'⎕FMT↑move ⍵
}</
{{out}}
Line 693:
=={{header|AppleScript}}==
<
-- hanoi :: Int -> (String, String, String) -> [(String, String)]
Line 770:
set my text item delimiters to dlm
str
end unlines</
{{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.)''
<
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)</
{{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</
{{out}}
Line 952:
{{trans|D}}
<
if n>0 [
hanoi n-1 f via dir
Line 960:
]
hanoi 3 'L 'M 'R</
{{out}}
Line 973:
=={{header|AutoHotkey}}==
<
{
if (n = 1)
Line 986:
}
}
move(64, 1, 3, 2)</
=={{header|AutoIt}}==
<
If ($n = 1) Then
ConsoleWrite(StringFormat("Move disk from pole "&$from&" To pole "&$to&"\n"))
Line 999:
EndFunc
move(4, 1,2,3)</
=={{header|AWK}}==
{{trans|Logo}}
<
BEGIN{hanoi(4,"left","middle","right")}'</
{{out}}
<pre>left -> right
Line 1,026:
{{works with|FreeBASIC}}
{{works with|RapidQ}}
<
IF n>0 THEN
move n-1, fromPeg, viaPeg, toPeg
Line 1,034:
END SUB
move 4,1,2,3</
===Using <code>GOSUB</code>s===
Line 1,041:
{{works with|Commodore BASIC}}
{{works with|GW-BASIC}}
<
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</
===Using binary method===
{{works with|Commodore BASIC}}
Very fast version in BASIC V2 on Commodore C-64
<
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</
{{out}}
<pre>1: 1 TO 3
Line 1,098:
=={{header|BASIC256}}==
<
print "Towers of Hanoi puzzle completed!"
end
Line 1,108:
call move(n-1, viaPeg, toPeg, fromPeg)
end if
end subroutine</
{{out}}
Line 1,131:
=={{header|Batch File}}==
<
setlocal enabledelayedexpansion
Line 1,158:
call :move !x! %via% %to% %from%
)
exit /b 0</
{{Out}}
<pre>Move top disk from pole START to pole HELPER.
Line 1,180:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
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</
=={{header|BCPL}}==
<
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)
$)</
{{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).
<
>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<</
{{out}}
Line 1,272:
'''Based on:''' [[APL]]
<
𝕩⊑⊸≤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</
<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"
┘</
=={{header|Bracmat}}==
<
= n from to via
. !arg:(?n,?from,?to,?via)
Line 1,310:
)
& move$(4,1,2,3)
);</
{{out}}
<pre>Move disk from pole 1 to pole 3
Line 1,330:
=={{header|Brainf***}}==
<
This implementation is recursive and uses
a stack, consisting of frames that are 8
Line 1,482:
>>[<<+>>-]<< step = next
<
]</
=={{header|C}}==
<
void move(int n, int from, int via, int to)
Line 1,501:
move(4, 1,2,3);
return 0;
}</
Animate it for fun:<
#include <stdlib.h>
#include <unistd.h>
Line 1,562:
text(1, 0, 1, "\n");
return 0;
}</
=={{header|C sharp|C#}}==
<
if (n == 1) {
System.Console.WriteLine("Move disk from pole " + from + " to pole " + to);
Line 1,573:
move(n - 1, via, to, from);
}
}</
=={{header|C++}}==
{{works with|g++}}
<
if (n == 1) {
std::cout << "Move disk from pole " << from << " to pole " << to << std::endl;
Line 1,585:
move(n - 1, via, to, from);
}
}</
=={{header|Clojure}}==
===Side-Effecting Solution===
<
(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)))</
===Lazy Solution===
<
(when (pos? n)
(lazy-cat (towers-of-hanoi (dec n) from via to)
(cons [from '-> to]
(towers-of-hanoi (dec n) via to from)))))</
=={{header|CLU}}==
<
po: stream := stream$primary_output()
if n > 0 then
Line 1,616:
start_up = proc ()
move(4, 1, 2, 3)
end start_up</
{{out}}
<pre>Move disk from pole 1 to pole 2
Line 1,637:
{{trans|C}}
{{works with|OpenCOBOL|2.0}}
<
IDENTIFICATION DIVISION.
PROGRAM-ID. towers-of-hanoi.
Line 1,664:
END-IF
.
END PROGRAM move-disk.</
{{ Number of disks also }}
<
IDENTIFICATION DIVISION.
PROGRAM-ID. towers-of-hanoi.
Line 1,697:
.
END PROGRAM move-disk.
</syntaxhighlight>
=== ANSI-74 solution ===
Line 1,705:
{{works with|CIS COBOL|4.2}}{{works with|GnuCOBOL|3.0-rc1.0}}
<
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>
=={{header|CoffeeScript}}==
<
if ndisks
staging_peg = 1 + 2 + 3 - start_peg - end_peg
Line 1,806:
hanoi(ndisks-1, staging_peg, end_peg)
hanoi(4)</
=={{header|Common Lisp}}==
<
(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))))</
=={{header|D}}==
===Recursive Version===
<
void hanoi(in int n, in char from, in char to, in char via) {
Line 1,831:
void main() {
hanoi(3, 'L', 'M', 'R');
}</
{{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]
<
// then some more by M. Kolar (2000).
void main(in string[] args) {
Line 1,884:
'\n'.putchar;
}
}</
{{out}}
<pre>| 3 2 1
Line 1,920:
=={{header|Dart}}==
<
moveit(from,to) {
print("move ${from} ---> ${to}");
Line 1,934:
hanoi(3,3,1,2);
}</
The same as above, with optional static type annotations and styled according to http://www.dartlang.org/articles/style-guide/
<
String say(String from, String to) => "$from ---> $to";
Line 1,949:
hanoi(3, 3, 1, 2);
}</
{{out}}
Line 2,047:
=={{header|Draco}}==
<
if n>0 then
move(n-1, src, dest, via);
Line 2,057:
proc nonrec main() void:
move(4, 1, 2, 3)
corp</
{{out}}
<pre>Move disk from pole 1 to pole 2
Line 2,079:
{{trans|Swift}}
<
if n > 0 {
hanoi(n - 1, a, c, b)
Line 2,087:
}
hanoi(4, "A", "B", "C")</
{{out}}
Line 2,108:
=={{header|E}}==
<
if (n.aboveZero()) {
move(out, n.previous(), fromPeg, viaPeg, toPeg)
Line 2,116:
}
move(stdout, 4, def left {}, def right {}, def middle {})</
=={{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</
=={{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.
<
[Towers of Hanoi task for Rosetta Code.]
[EDSAC program, Initial Orders 2.]
Line 2,288:
PF [acc = 0 on entry]
[end]
</syntaxhighlight>
{{out}}
<pre>
Line 2,302:
=={{header|Eiffel}}==
<
APPLICATION
Line 2,329:
end
end
end</
=={{header|Ela}}==
{{trans|Haskell}}
<
:::IO
Line 2,349:
hanoiM' (n - 1) a c b
putStrLn $ "Move " ++ show a ++ " to " ++ show b
hanoiM' (n - 1) c b a</
=={{header|Elena}}==
ELENA 4.x :
<
{
if (n == 1)
Line 2,365:
move(n-1,via,to,from)
}
};</
=={{header|Elixir}}==
<
def hanoi(n) when 0<n and n<10, do: hanoi(n, 1, 2, 3)
Line 2,381:
end
RC.hanoi(3)</
{{out}}
Line 2,396:
=={{header|Emacs Lisp}}==
{{Trans|Common Lisp}}
<
(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)))</
=={{header|Erlang}}==
<
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).</
=={{header|ERRE}}==
<
!-----------------------------------------------------------
! HANOI.R : solve tower of Hanoi puzzle using a recursive
Line 2,468:
MOVE
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 2,491:
{{Works with| Office 365 Betas 2021}}
<
=LAMBDA(n,
FILTERP(
Line 2,524:
)
)
)</
And assuming that these generic lambdas are also bound to the following names in Name Manager:
<
=LAMBDA(xs,
LAMBDA(ys,
Line 2,553:
FILTER(xs, p(xs))
)
)</
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">
# (C) 2013 Ezhil Language Project
# Tower of Hanoi – recursive solution
Line 2,629:
ஹோனாய்(4,”அ”,”ஆ”,0)
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
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</
=={{header|Factor}}==
<
IN: rosettacode.hanoi
Line 2,656:
from to move
n 1 - other to from hanoi
] when ;</
In the REPL:
<pre>( scratchpad ) 3 1 3 2 hanoi
Line 2,668:
=={{header|FALSE}}==
<
"]p: { to from }
[n;0>[n;1-n: @\ h;! @\ p;! \@ h;! \@ n;1+n:]?]h: { via to from }
4n:["right"]["middle"]["left"]h;!%%%</
=={{header|Fermat}}==
<
if n = 0 then
!'';
Line 2,681:
!f;!' -> ';!t;!', ';
Hanoi(n - 1, v, t, f)
fi.</
{{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}}==
<
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),!</
{{out}}
Line 2,723:
=={{header|Forth}}==
With locals:
<
CREATE peg2 ," middle "
CREATE peg3 ," right "
Line 2,735:
1 from to via RECURSE
n 1- via to from RECURSE
THEN ;</
Without locals, executable pegs:
<
: right ." right" ;
: middle ." middle" ;
Line 2,750:
swap rot ;
: hanoi ( n -- )
1 max >R ['] right ['] middle ['] left R> move-disk drop drop drop ;</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
CALL Move(4, 1, 2, 3)
Line 2,772:
END SUBROUTINE Move
END PROGRAM TOWER</
{{ More informative version }}
<
PROGRAM TOWER2
Line 2,794:
END SUBROUTINE Move
END PROGRAM TOWER2 </
=={{header|FreeBASIC}}==
<
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</
{{out}}
Line 2,847:
=={{header|Frink}}==
<
/** Set up the recursive call for n disks */
hanoi[n] := hanoi[n, 1, 3, 2]
Line 2,863:
hanoi[7]
</syntaxhighlight>
=={{header|FutureBasic}}==
<
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</
Output:
Line 2,912:
=={{header|GAP}}==
<
local move;
move := function(n, a, b, c) # from, through, to
Line 2,941:
# B -> A
# B -> C
# A -> C</
=={{header|Go}}==
<
import "fmt"
Line 2,985:
func (t *towers) move1(from, to int) {
fmt.Println("move disk from rod", from, "to rod", to)
}</
In other words:
<
import "fmt"
Line 3,003:
move(n-1, b, a, c)
}
}</
=={{header|Groovy}}==
Unlike most solutions here this solution manipulates more-or-less actual stacks of more-or-less actual rings.
<
final STACK = [A:[],B:[],C:[]].asImmutable()
Line 3,023:
moveRing(from, to)
moveStack(tail(using, n-1), to, from)
}</
Test program:
<
S('°'), M('o'), L('O'), XL('( )');
private sym
Line 3,038:
report()
check(STACK.A)
moveStack(STACK.A, STACK.C)</
{{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:
<
hanoi 0 _ _ _ = []
hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a</
You can also do the above with one tail-recursion call:
<
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)</
One can use this function to produce output, just like the other programs:
<
f (x,y) = putStrLn $ "Move " ++ show x ++ " to " ++ show y</
or, instead, one can of course also program imperatively, using the IO monad directly:
<
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</
or, defining it as a monoid, and adding some output:
<
hanoi ::
Line 3,163:
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</
{{Out}}
<pre> left -> right
Line 3,199:
=={{header|HolyC}}==
{{trans|C}}
<
if (n > 0) {
Move(n - 1, from, via, to);
Line 3,207:
}
Move(4, 1, 2, 3);</
=={{header|Icon}} and {{header|Unicon}}==
The following is based on a solution in the Unicon book.
<
hanoi(arglist[1]) | stop("Usage: hanoi n\n\rWhere n is the number of disks to move.")
end
Line 3,233:
}
return
end</
=={{header|Inform 7}}==
<
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.</
=={{header|Io}}==
<
if (n == 1) then (
writeln("Move from ", from, " to ", to)
Line 3,271:
hanoi(n - 1, via , to , from)
)
)</
=={{header|Ioke}}==
<
if(n < 2,
"#{f} --> #{t}" println,
Line 3,286:
hanoi = method(n,
H(n, 1, 2, 3)
)</
=={{header|IS-BASIC}}==
<
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</
=={{header|J}}==
'''Solutions'''
<
{{out|Example use}}
<
0 2
0 1
Line 3,310:
1 2
1 0
2 0</
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:
<
if. y do.
({&0 2 1 , 0 2 , {&1 0 2) H1 y-1
Line 3,319:
i.0 2
end.
)</
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):
<
moves=. H y
disks=. $~` ((],[,]) $:@<:) @.* y
('move disk ';' from peg ';' to peg ');@,."1 ":&.>disks,.1+moves
)</
{{out|Demonstration}}
<
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</
=={{header|Java}}==
<
if (n == 1) {
System.out.println("Move disk from pole " + from + " to pole " + to);
Line 3,351:
move(n - 1, via, to, from);
}
}</
=={{header|JavaScript}}==
===ES5===
<
if (n > 0) {
move(n-1, a, c, b);
Line 3,362:
}
}
move(4, "A", "B", "C");</
Or, as a functional expression, rather than a statement with side effects:
<
// hanoi :: Int -> String -> String -> String -> [[String, String]]
Line 3,382:
return d[0] + ' -> ' + d[1];
});
})();</
{{Out}}
<
"right -> mid", "left -> right",
"mid -> left", "mid -> right",
"left -> right"]</
===ES6===
<
"use strict";
Line 3,416:
.map(d => `${d[0]} -> ${d[1]}`)
.join("\n");
})();</
{{Out}}
<pre>left -> right
Line 3,427:
=={{header|Joy}}==
<syntaxhighlight lang=
[[[null] [pop pop] ]
[[dup2 [[rotate] infra] dip pred]
Line 3,435:
condnestrec.</syntaxhighlight>
Using it (5 is the number of disks.)
<syntaxhighlight lang=
=={{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.
<
def move(n; From; To; Via):
if n > 0 then
Line 3,461:
move(n-1; Via; To; From)
else empty
end;</
'''Example''':
move(5; "A"; "B"; "C")
Line 3,467:
=={{header|Jsish}}==
From Javascript ES5 entry.
<
function move(n, a, b, c) {
Line 3,497:
Move disk from B to C
=!EXPECTEND!=
*/</
{{out}}
Line 3,505:
=={{header|Julia}}==
{{trans|R}}
<
function solve(n::Integer, from::Integer, to::Integer, via::Integer)
if n == 1
Line 3,517:
solve(4, 1, 2, 3)
</syntaxhighlight>
{{out}}
Line 3,539:
=={{header|K}}==
<
h[4;1;2;3]
1:1->3
Line 3,555:
1:1->3
2:1->2
1:3->2</
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.
<
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</
=={{header|Klingphix}}==
{{trans|MiniScript}}
<
:moveDisc %B !B %C !C %A !A %n !n { n A C B }
Line 3,578:
3 1 3 2 moveDisc
" " input</
{{out}}
<pre>Move disc 1 from pole 1 to pole 3
Line 3,589:
=={{header|Kotlin}}==
<
class Hanoi(disks: Int) {
Line 3,613:
Hanoi(3)
Hanoi(4)
}</
{{out}}
Line 3,652:
=={{header|lambdatalk}}==
(Following NewLisp, PicoLisp, Racket, 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>
=={{header|Lasso}}==
<
define towermove(
Line 3,693:
}
towermove((integer($argv -> second || 3)), "A", "B", "C")</
Called from command line:
<syntaxhighlight lang
{{out}}
<pre>Move disk from A to C
Line 3,705:
Move disk from A to C</pre>
Called from command line:
<syntaxhighlight lang
{{out}}
<pre>Move disk from A to B
Line 3,725:
=={{header|Liberty BASIC}}==
This looks much better with a GUI interface.
<
via$ ="B"
target$ ="C"
Line 3,743:
end sub
end</
=={{header|Lingo}}==
<
if n > 0 then
hanoi(n-1, a, c, b)
Line 3,752:
hanoi(n-1, b, a, c)
end if
end</
<
-- "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"</
=={{header|Logo}}==
<
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</
=={{header|Logtalk}}==
<
:- public(run/1).
Line 3,800:
nl.
:- end_object.</
=={{header|LOLCODE}}==
<
HOW IZ I HANOI YR N AN YR SRC AN YR DST AN YR VIA
Line 3,822:
KTHXBYE
</syntaxhighlight>
=={{header|Lua}}==
<
if n > 0 then
move(n - 1, src, via, dst)
Line 3,833:
end
move(4, 1, 2, 3)</
{{More informative version }}
<syntaxhighlight lang="lua">
function move(n, src, via, dst)
Line 3,849:
move(4, 1, 2, 3)
</syntaxhighlight>
===Hanoi Iterative===
<
#!/usr/bin/env luajit
local function printf(fmt, ...) io.write(string.format(fmt, ...)) end
Line 3,893:
hanoi(num)
</syntaxhighlight>
{{out}}
<pre>
Line 3,901:
===Hanoi Bitwise Fast===
<
#!/usr/bin/env luajit
-- binary solution
Line 3,916:
hanoi(num)
</syntaxhighlight>
{{out}}
<pre>
Line 3,927:
=={{header|M2000 Interpreter}}==
{{trans|FreeBasic}}
<syntaxhighlight lang="m2000 interpreter">
Module Hanoi {
Rem HANOI TOWERS
Line 3,945:
}
Hanoi
</syntaxhighlight>
{{out}}
same as in FreeBasic
Line 3,951:
=={{header|MAD}}==
<
DIMENSION LIST(100)
SET LIST TO LIST
Line 3,988:
END OF PROGRAM
</syntaxhighlight>
{{out}}
Line 4,010:
=={{header|Maple}}==
<syntaxhighlight 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>
{{out}}
Line 4,036:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
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])</
=={{header|MATLAB}}==
This is a direct translation from the Python example given in the Wikipedia entry for the Tower of Hanoi puzzle.
<
if (n~=0)
towerOfHanoi(n-1,A,B,C);
Line 4,047:
towerOfHanoi(n-1,B,C,A);
end
end</
{{out|Sample output}}
<pre>towerOfHanoi(3,1,3,2)
Line 4,059:
=={{header|MiniScript}}==
<
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</
{{out}}
<pre>Move disc 1 from pole 1 to pole 3
Line 4,091:
hanoi(3)
--><
# Towers of Hanoi
# MIPS assembly implementation (tested with MARS)
Line 4,193:
beq $s0, $t1, exithanoi
j recur2
</syntaxhighlight>
=={{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 С/П В/О</
Instruction: РA = 56; РB = 60; РC = 72; N В/О С/П, where 2 <= N <= 7.
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
Line 4,228:
ReadChar
END Towers.</
=={{header|Modula-3}}==
<
FROM IO IMPORT Put;
Line 4,247:
BEGIN
doHanoi(4, 1, 2, 3);
END Hanoi.</
=={{header|Monte}}==
<
if (n > 0):
move(n.previous(), fromPeg, viaPeg, toPeg)
Line 4,256:
move(n.previous(), viaPeg, toPeg, fromPeg)
move(3, "left", "right", "middle")</
=={{header|MoonScript}}==
<
if n > 1
hanoi n-1, src, via, dest
Line 4,266:
hanoi n-1, via, dest, src
hanoi 4,1,3,2</
{{Out}}
<pre>1 -> 2
Line 4,284:
2 -> 3</pre>
=={{header|Nemerle}}==
<
using System.Console;
Line 4,303:
Hanoi(4)
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols binary
Line 4,333:
end
return moves
</syntaxhighlight>
{{out}}
<pre>
Line 4,356:
=={{header|NewLISP}}==
<
(if (> n 0)
(move (- n 1) from via to
Line 4,362:
(move (- n 1) via to from))))
(move 4 1 2 3)</
=={{header|Nim}}==
<
if disks != 0:
hanoi(disks - 1, fromTower, viaTower, toTower)
Line 4,371:
hanoi(disks - 1, viaTower, toTower, fromTower)
hanoi(4, "1", "2", "3")</
{{out}}
<pre>Move disk 1 from 1 to 3
Line 4,390:
=={{header|Objeck}}==
<
function : Main(args : String[]) ~ Nil {
Move(4, 1, 2, 3);
Line 4,405:
};
}
}</
=={{header|Objective-C}}==
Line 4,414:
The Interface - TowersOfHanoi.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</
The Implementation - TowersOfHanoi.m:
<
@implementation TowersOfHanoi
Line 4,447:
}
@end</
Test code: TowersTest.m:
<
#import "TowersOfHanoi.h"
Line 4,468:
}
return 0;
}</
=={{header|OCaml}}==
<
if n <> 0 then begin
hanoi (pred n) a c b;
Line 4,479:
let () =
hanoi 4 1 2 3</
=={{header|Octave}}==
<
if ( ndisks == 1 )
printf("Move disk from pole %d to pole %d\n", from, to);
Line 4,492:
endfunction
hanoimove(4, 1, 2, 3);</
=={{header|Oforth}}==
<
n 0 > ifTrue: [
move(n 1-, from, via, to)
Line 4,503:
] ;
5 $left $middle $right) move </
=={{header|Oz}}==
<
proc {TowersOfHanoi N From To Via}
if N > 0 then
Line 4,515:
end
in
{TowersOfHanoi 4 left middle right}</
=={{header|PARI/GP}}==
{{trans|Python}}
<
\\ 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);</
{{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.
<
type
TPole = (tpLeft, tpCenter, tpRight);
Line 4,565:
begin
MoveStack(4,tpLeft,tpCenter,tpRight);
end.</
A little longer, but clearer for my taste
<
type
TPole = (tpLeft, tpCenter, tpRight);
Line 4,591:
begin
MoveStack(4,tpLeft,tpCenter,tpRight);
end.</
=={{header|Perl}}==
<
my ($n, $from, $to, $via) = (@_, 1, 2, 3);
Line 4,604:
hanoi($n - 1, $via, $to, $from);
};
};</
=={{header|Phix}}==
<!--<
<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>
<!--</
{{Out}}
<pre style="float:left">
Line 4,773:
{{trans|C}}
<
extern printf;
Line 4,788:
move(4, 1,2,3);
return 0;
]</
=={{header|PHP}}==
{{trans|Java}}
<
if ($n === 1) {
print("Move disk from pole $from to pole $to");
Line 4,800:
move($n-1,$via,$to,$from);
}
}</
=={{header|Picat}}==
<
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>
{{out}}
Line 4,825:
===Fast counting===
<
hanoi(64).
Line 4,839:
Count2 = move(N - 1, Via, To, From),
Count = Count1+Count2+1.
</syntaxhighlight>
{{out}}
<pre>
Line 4,846:
=={{header|PicoLisp}}==
<
(unless (=0 N)
(move (dec N) A C B)
(println 'Move 'disk 'from A 'to B)
(move (dec N) C B A) ) )</
=={{header|PL/I}}==
{{trans|Fortran}}
<
call Move (4,1,2,3);
Line 4,872:
end Move;
end tower;</
=={{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)
<
/* CP/M BDOS SYSTEM CALL */
Line 4,902:
CALL PR$STRING( .( 0DH, 0AH, '$' ) );
END;
EOF</
{{out}}
<pre>
Line 4,924:
=={{header|PlainTeX}}==
<
\def\hanoi#1{%
\hanoidepth = #1
Line 4,942:
\hanoi{5}
\end</
=={{header|Pop11}}==
<
if n > 0 then
hanoi(n - 1, src, via, dst);
Line 4,953:
enddefine;
hanoi(4, "left", "middle", "right");</
=={{header|PostScript}}==
A million-page document, each page showing one move.
<
%%BoundingBox: 0 0 300 300
Line 5,004:
drawtower 0 1 2 n hanoi
%%EOF</
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
function hanoi($n, $a, $b, $c) {
if($n -eq 1) {
Line 5,020:
}
hanoi 3 "A" "B" "C"
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 5,034:
=={{header|Prolog}}==
From Programming in Prolog by W.F. Clocksin & C.S. Mellish
<
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.</
Using DCGs and separating core logic from IO
<
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>
=={{header|PureBasic}}==
Algorithm according to http://en.wikipedia.org/wiki/Towers_of_Hanoi
<
If n
Hanoi(n-1, A, B, C)
Line 5,074:
Hanoi(n-1, B, C, A)
EndIf
EndProcedure</
Full program
<
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</
{{out}}
Moving 3 pegs.
Line 5,105:
=={{header|Python}}==
===Recursive===
<
if ndisks:
hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
Line 5,111:
hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)
hanoi(4)</
{{out}} for ndisks=2
<pre>
Line 5,122:
Or, separating the definition of the data from its display:
{{Works with|Python|3.7}}
<
Line 5,149:
print(__doc__ + ':\n\n' + '\n'.join(
map(fromTo, hanoi(4)('left')('right')('mid'))
))</
{{Out}}
<pre>Towers of Hanoi:
Line 5,173:
Refactoring the version above to recursively generate a simple visualisation:
{{Works with|Python|3.7}}
<
from itertools import accumulate, chain, repeat
Line 5,369:
# TEST ----------------------------------------------------
if __name__ == '__main__':
main()</
<pre>Hanoi sequence for 3 disks:
Line 5,418:
=={{header|Quackery}}==
<
[ rings share
Line 5,438:
say 'How to solve a three ring Towers of Hanoi puzzle:' cr cr
3 hanoi cr</
{{out}}
Line 5,465:
'This is implemented on the Quite BASIC website
'http://www.quitebasic.com/prj/puzzle/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</
=={{header|R}}==
{{trans|Octave}}
<
if (ndisks == 1) {
cat("move disk from", from, "to", to, "\n")
Line 5,652:
}
hanoimove(4, 1, 2, 3)</
=={{header|Racket}}==
<
#lang racket
(define (hanoi n a b c)
Line 5,663:
(hanoi (- n 1) c b a)))
(hanoi 4 'left 'middle 'right)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
multi hanoi (0, Peg $a, Peg $b, Peg $c) { }
Line 5,674:
say "Move $a to $b.";
hanoi $n - 1, $c, $b, $a;
}</
=={{header|Rascal}}==
{{trans|Python}}
<
if(ndisks>0){
hanoi(ndisks-1, startPeg, 6 - startPeg - endPeg);
Line 5,684:
hanoi(ndisks-1, 6 - startPeg - endPeg, endPeg);
}
}</
{{out}}
<
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</
=={{header|Raven}}==
{{trans|Python}}
<
ndisks 0 > if
6 startpeg - endpeg - startpeg ndisks 1 - hanoi
Line 5,718:
# 4 disks
4 dohanoi
</syntaxhighlight>
{{out}}
<pre>raven hanoi.rv
Line 5,739:
=={{header|REBOL}}==
<
Title: "Towers of Hanoi"
URL: http://rosettacode.org/wiki/Towers_of_Hanoi
Line 5,759:
]
hanoi 4</
{{out}}
<pre>left -> right
Line 5,778:
=={{header|Retro}}==
<
{ 'Num 'From 'To 'Via } [ var ] a:for-each
Line 5,791:
#3 #1 #3 #2 hanoi nl
[[User:Wodan58|Wodan58]] ([[User talk:Wodan58|talk]])</
=={{header|REXX}}==
===simple text moves===
<
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.*/</
{{out|output|text= 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.
<
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</
{{out|output|text= when using the default input:}}
<pre>
Line 5,970:
=={{header|Ring}}==
<
move(4, 1, 2, 3)
Line 5,977:
see "" + src + " to " + dst + nl
move(n - 1, via, dst, src) ok
</syntaxhighlight>
=={{header|Ruby}}==
===version 1===
<
if num_disks == 1
@towers[target] << @towers[start].pop
Line 5,994:
n = 5
@towers = [[*1..n].reverse, [], []]
move(n)</
{{out}}
Line 6,032:
===version 2===
<
# Example:
# solve([5, 4, 3, 2, 1], [], [])
Line 6,060:
end
solve([5, 4, 3, 2, 1], [], [])</
{{out}}
<pre>
Line 6,098:
=={{header|Run BASIC}}==
<
function move(n, a$, b$, c$)
if n > 0 then
Line 6,105:
a = move(n-1, b$, a$, c$)
end if
end function</
<pre>Move disk from 1 to 3
Move disk from 1 to 2
Line 6,124:
=={{header|Rust}}==
{{trans|C}}
<
if n > 0 {
move_(n - 1, from, via, to);
Line 6,134:
fn main() {
move_(4, 1,2,3);
}</
=={{header|SASL}}==
Copied from SAL manual, Appendix II, answer (3)
<
WHERE
hanoi 0 (a,b,c,) = ()
Line 6,144:
‘move a disc from " , a , ‘ to " , b , NL ,
hanoi (n-1) (c,b,a)
?</
=={{header|Sather}}==
{{trans|Fortran}}
<
move(ndisks, from, to, via:INT) is
Line 6,163:
move(4, 1, 2, 3);
end;
end;</
=={{header|Scala}}==
<
if (n == 1) {
Console.println("Move disk from pole " + from + " to pole " + to)
Line 6,174:
move(n - 1, via, to, from)
}
}</
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
<
import scala.reflect.Manifest
Line 6,211:
run[_2,Left,Right,Center]
}
}</
=={{header|Scheme}}==
Recursive Process
<
(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")</
{{out}}
<pre>Move[A, B]
Line 6,241:
=={{header|Seed7}}==
<
begin
if disk > 0 then
Line 6,248:
hanoi(pred(disk), via, dest, source);
end if;
end func;</
=={{header|Sidef}}==
{{trans|Perl}}
<
if (n == 1) {
say "Move disk from pole #{from} to pole #{to}.";
Line 6,262:
}
hanoi(4);</
=={{header|SNOBOL4}}==
<
define('hanoi(n,src,trg,tmp)') :(hanoi_end)
Line 6,277:
* # Test with 4 discs
hanoi(4,'A','C','B')
end</
{{out}}
<pre>1: Move disc from A to B
Line 6,301:
=={{header|Stata}}==
<
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</
=={{header|Swift}}==
{{trans|JavaScript}}
<
if (n > 0) {
hanoi(n - 1, a, c, b)
Line 6,329:
}
hanoi(4, "A", "B", "C")</
'''Swift 2.1'''
<
if (n > 0) {
hanoi(n - 1, a: a, b: c, c: b)
Line 6,340:
}
hanoi(4, a:"A", b:"B", c:"C")</
=={{header|Tcl}}==
The use of <code>interp alias</code> shown is a sort of closure: keep track of the number of moves required
<
proc do_hanoi {count n {from A} {to C} {via B}} {
Line 6,358:
}
hanoi 4</
{{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.
<
0→A
1→B
Line 6,459:
End
</syntaxhighlight>
=={{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.
<
INPUT D
IF D < 1 THEN GOTO 5
Line 6,510:
LET Z = Z / 2
IF Z = 0 THEN RETURN
GOTO 55</
{{out}}<pre>
Line 6,533:
=={{header|Toka}}==
<
[ 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</
=={{header|True BASIC}}==
{{trans|FreeBASIC}}
<
DECLARE SUB hanoi
Line 6,571:
PRINT "Pulsa un tecla para salir"
END
</syntaxhighlight>
=={{header|TSE SAL}}==
<
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</
=={{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</
=={{header|UNIX Shell}}==
Line 6,618:
{{works with|Korn Shell}}
{{works with|Z Shell}}
<
typeset -i n=$1
typeset from=$2
Line 6,631:
}
move "$@"</
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}}
<
if [ "$1" -gt 0 ]; then
"$0" "`expr $1 - 1`" "$2" "$4" "$3"
Line 6,642:
"$0" "`expr $1 - 1`" "$4" "$3" "$2"
fi
</syntaxhighlight>
Output from any of the above:
Line 6,664:
=={{header|Ursala}}==
<
move = ~&al^& ^rlPlrrPCT/~&arhthPX ^|W/~& ^|G/predecessor ^/~&htxPC ~&zyxPC
Line 6,670:
#show+
main = ^|T(~&,' -> '--)* move/4 <'start','end','middle'></
{{out}}
<pre>start -> middle
Line 6,690:
=={{header|VBScript}}==
Derived from the BASIC256 version.
<
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!")</
{{out}}
Line 6,722:
=={{header|Vedit macro language}}==
This implementation outputs the results in current edit buffer.
<
Call("MOVE_DISKS")
Return
Line 6,746:
Num_Pop(1,4)
}
Return</
=={{header|Vim Script}}==
<
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)</
{{Out}}
Line 6,779:
=={{header|Visual Basic .NET}}==
<
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</
=={{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.
<
1010 F=1
1020 T=2
Line 6,845:
5080 R=:S)
5090 S=S-1
5100 #=!</
{{out}}
<pre>
Line 6,867:
=={{header|Wren}}==
{{trans|Kotlin}}
<
construct new(disks) {
_moves = 0
Line 6,886:
Hanoi.new(3)
Hanoi.new(4)</
{{out}}
Line 6,924:
=={{header|XPL0}}==
<
proc MoveTower(Discs, From, To, Using);
Line 6,936:
];
MoveTower(3, "left", "right", "center")</
{{out}}
Line 6,950:
=={{header|XQuery}}==
<
$to as xs:integer, $via as xs:integer) as element()*
{
Line 6,966:
local:hanoi(4, 1, 2, 3)
}
</hanoi></
{{out}}
<
<hanoi>
<move disk="1">
Line 7,030:
<to>2</to>
</move>
</hanoi></
=={{header|XSLT}}==
<
<xsl:param name="n"/>
<xsl:param name="from">left</xsl:param>
Line 7,058:
</xsl:call-template>
</xsl:if>
</xsl:template></
<xsl:call-template name="hanoi"><xsl:with-param name="n" select="4"/></xsl:call-template>
=={{header|Yabasic}}==
<
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"</
=={{header|Zig}}==
{{trans|C}}
<
pub fn print(from: u32, to: u32) void {
Line 7,116:
}
</syntaxhighlight>
=={{header|zkl}}==
{{trans|C}}
<
if (n>0){
move(n-1, from,via,to);
Line 7,127:
}
}
move(3, 1,2,3);</
{{out}}
<pre>
|