How does this work? Weird Towers of Hanoi Solution

前端 未结 3 1863
故里飘歌
故里飘歌 2020-11-29 17:24

I was lost on the internet when I discovered this unusual, iterative solution to the towers of Hanoi:

for (int x = 1; x         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 17:35

    antti.huima's solution is essentially correct, but I wanted something more rigorous, and it was too big to fit in a comment. Here goes:

    First note: at the middle step x = 2N-1 of this algorithm, the "from" peg is 0, and the "to" peg is 2N % 3. This leaves 2(N-1) % 3 for the "spare" peg. This is also true for the last step of the algorithm, so we see that actually the authors' algorithm is a slight "cheat": they're moving the disks from peg 0 to peg 2N % 3, rather than a fixed, pre-specified "to" peg. This could be changed with not much work.

    The original Hanoi algorithm is:

    hanoi(from, to, spare, N):
        hanoi(from, spare, to, N-1)
        move(from, to)
        hanoi(spare, to, from, N-1)
    

    Plugging in "from" = 0, "to" = 2N % 3, "spare" = 2N-1 % 3, we get (suppressing the %3's):

    hanoi(0, 2**N, 2**(N-1), N):
    (a)   hanoi(0, 2**(N-1), 2**N, N-1)
    (b)   move(0, 2**N)
    (c)   hanoi(2**(N-1), 2**N, 0, N-1)
    

    The fundamental observation here is: In line (c), the pegs are exactly the pegs of hanoi(0, 2N-1, 2N, N-1) shifted by 2N-1 % 3, i.e. they are exactly the pegs of line (a) with this amount added to them.

    I claim that it follows that when we run line (c), the "from" and "to" pegs are the corresponding pegs of line (a) shifted by 2N-1 % 3. This follows from the easy, more general lemma that in hanoi(a+x, b+x, c+x, N), the "from and "to" pegs are shifted exactly x from in hanoi(a, b, c, N).

    Now consider the functions
    f(x) = (x & (x-1)) % 3
    g(x) = (x | (x-1)) + 1 % 3

    To prove that the given algorithm works, we only have to show that:

    • f(2N-1) == 0 and g(2N-1) == 2N
    • for 0 < i < 2N, we have f(2N - i) == f(2N + i) + 2N % 3, and g(2N - i) == g(2N + i) + 2N % 3.

    Both of these are easy to show.

提交回复
热议问题