Jump to content

Towers of Hanoi: Difference between revisions

Simpler first D version
(adding gap)
(Simpler first D version)
Line 206:
=={{header|D}}==
===Recursive===
<lang d>moduleimport hanoistd.stdio;
}
import std.stdio;
void hanoi(int n, char from, char to, char via) {
 
return if (n > 0) ? {
struct Hanoi {
hanoi(n - 1, from, via, to);
static Hanoi opCall(int n, string src, string dst, string via) {
writefln("Move disk %sd from %s to %s", n, srcfrom, dstto) ;
return (n > 0) ?
Hanoi(n - 1, src, via, dst)(n, src, dst) hanoi(n - 1, via, dstto, srcfrom);
}
: Hanoi.init ;
}
static Hanoi opCall(int n, string src, string dst) {
writefln("Move disk %s from %s to %s", n, src, dst) ;
return Hanoi.init ;
}
}
 
void main() {
Hanoi hanoi(3, "'L"'," 'M"'," 'R"') ;
}</lang>
Output:
<pre>Move disk 1 from L to M
Move disk 2 from L to R
Move disk 1 from M to R
Move disk 3 from L to M
Move disk 1 from R to L
Move disk 2 from R to M
Move disk 1 from L to M</pre>
 
===Iterative===
ref : [http://hanoitower.mkolar.org/shortestTHalgo.html The shortest and "mysterious" TH algorithm]
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.