towers-of-hanoi

How does this work? Weird Towers of Hanoi Solution

旧街凉风 提交于 2019-11-26 10:14:09
问题 I was lost on the internet when I discovered this unusual, iterative solution to the towers of Hanoi: for (int x = 1; x < (1 << nDisks); x++) { FromPole = (x & x-1) % 3; ToPole = ((x | x-1) + 1) % 3; moveDisk(FromPole, ToPole); } This post also has similar Delphi code in one of the answers. However, for the life of me, I can\'t seem to find a good explanation for why this works. Can anyone help me understand it? 回答1: the recursive solution to towers of Hanoi works so that if you want to move

Tower of Hanoi: Recursive Algorithm

谁说胖子不能爱 提交于 2019-11-26 06:50:39
Although I have no problem whatsoever understanding recursion, I can't seem to wrap my head around the recursive solution to the Tower of Hanoi problem. Here is the code from Wikipedia : procedure Hanoi(n: integer; source, dest, by: char); Begin if (n=1) then writeln('Move the plate from ', source, ' to ', dest) else begin Hanoi(n-1, source, by, dest); writeln('Move the plate from ', source, ' to ', dest); Hanoi(n-1, by, dest, source); end; End; I understand the base case and the concept of breaking the problem into smaller pieces until you are able to move a single disk. However, I can't

Tower of Hanoi: Recursive Algorithm

你。 提交于 2019-11-26 00:32:58
问题 Although I have no problem whatsoever understanding recursion, I can\'t seem to wrap my head around the recursive solution to the Tower of Hanoi problem. Here is the code from Wikipedia: procedure Hanoi(n: integer; source, dest, by: char); Begin if (n=1) then writeln(\'Move the plate from \', source, \' to \', dest) else begin Hanoi(n-1, source, by, dest); writeln(\'Move the plate from \', source, \' to \', dest); Hanoi(n-1, by, dest, source); end; End; I understand the base case and the