Towers of Hanoi: Difference between revisions
Content added Content deleted
(Simpler first D version) |
(Fixed second D version) |
||
Line 229:
===Iterative===
<lang d>// Code found and then improved by Glenn C. Rhoads,
// then some more by M. Kolar (2000).
import std.stdio;▼
▲import std.stdio, std.conv, std.typetuple;
int nn = (1 << n) ;▼
for(x = 1 ; x < nn ; x++){▼
i = x & x - 1 ; fr = (i + i/3) & 3 ;▼
i = (x | x - 1) + 1 ; to = (i + i/3) & 3 ;▼
for(i = x, j = 1; !(i&1) ; i >>=1, j++) ▼
}▼
void main(string[] args) {
size_t[3] p;
printf("\n|");
printf(" %d", i);
printf("\n|\n|\n");
foreach (size_t x; 1 .. (1 << n)) {
i = x & (x - 1);
i = (x | (x - 1)) + 1;
if (i & 1)
break;
// Now j is not the number of the disk to move,
// it contains the single bit to be moved:
p[fr] &= ~j;
p[to] |= j;
foreach (k; TypeTuple!(0, 1, 2)) {
printf("\n|");
j = 1 << n;
for (i = n; i > 0; i--) {
j >>= 1;
if (j & p[k])
printf(" %d", i);
}
}
printf("\n");
▲ }
}</lang>
Output:
<pre>| 3 2 1
|
|
| 3 2
|
| 1
| 3
| 2
| 1
| 3
| 2 1
|
|
| 2 1
| 3
| 1
| 2
| 3
| 1
|
| 3 2
|
|
| 3 2 1</pre>
=={{header|Dc}}==
|