3 ms·
We can actually solve Towers of Hanoi non-recursively by manipulating bits: max = 1 << no_of_discs; for (x = 1; x < max; x++) printf("move a di
by tromp 7y ago
We can actually solve Towers of Hanoi non-recursively by manipulating bits:
max = 1 << no_of_discs;
for (x = 1; x < max; x++)
printf("move a disc from %d to %d\n", (x&x-1)%3, ((x|x-1)+1)%3);
where x&x-1 is smaller than x as much as (x|x-1)+1 is larger than x, by a 2-power corresponding to the least significant 1-bit in x.
- deleted 7y ago[deleted]
- bear8642 7y agoCould you explain why that's true? - get that it works but don't understand why
- tromp 7y agoI never constructed a proof either, but it would rest on the observation that the i'th smallest disc (i=1..no_of_discs) moves every 2^i-th step in the same direction (+1 mod 3 for odd i and -1 mod 3 for even i).