Towers of Hanoi: Difference between revisions

Updated the iterative D version
(→‎{{header|Euphoria}}: Euphoria example added)
(Updated the iterative D version)
Line 230:
===Iterative===
Fast iterative version. See: [http://hanoitower.mkolar.org/shortestTHalgo.html The shortest and "mysterious" TH algorithm]
<lang d>import std.stdio, std.conv, std.typetuple;
<lang d>// Code found and then improved by Glenn C. Rhoads,
 
// then some more by M. Kolar (2000).
import std.stdio, std.conv, std.typetuple;
void main(string[] args) {
<lang d> // Code found and then improved by Glenn C. Rhoads,
const n = (args.length > 1) ? to!int(args[1]) : 3;
// then some more by M. Kolar (2000).
size_t i, j;
 
size_t[3] p;
p[0]immutable size_t n = (1args.length <<> n1) -? to!size_t(args[1]) : 3;
size_t[3] p = [(1 << n) - 1, 0, 0];
 
printf("\n|");
forforeach_reverse (size_t i = n; i1 >.. 0; i--n+1)
printf(" %d", i);
printf("\n|\n|\n");
 
foreach (size_t x; 1 .. (1 << n)) {
i = x & (x - 1);{
const size_t fr = (iimmutable +size_t ii1 /= 3)x & 3(x - 1);
i immutable size_t fr = (xi1 |+ (xi1 -/ 1)3) +& 13;
const immutable size_t toi2 = (ix +| i(x /- 31)) &+ 31;
immutable size_t to = (i2 + i2 / 3) & 3;
 
for (i = x, j = 1; ; i >>= 1, j <<= 1)
ifsize_t (ij &= 1);
for (int w = breakx; ; w >>= 1, j <<= 1)
for (i = x, j = 1; ; iif >>= 1, j(w <<=& 1)
// Now j is not the number of the disk to move, break;
 
// it contains the single bit to be moved:
// Now j is not the number of the disk to move,
p[fr] &= ~j;
p[ // it contains the single bit to] |=be j;moved:
p[fr] &= ~j;
foreach (k; TypeTuple!(0, 1, 2))p[to] {|= j;
}
 
foreach (size_t k; TypeTuple!(0, 1, 2)) {
printf("\n|");
size_t j = 1 << n;
forforeach_reverse (isize_t = nw; i1 >.. 0; i--n+1) {
j >>= 1;
if (j & p[k])
printf(" %du", iw);
}
}
 
printfputchar("'\n"');
}
}</lang>
Anonymous user