The basics of programming in c++ for beginners

A task: tower of Hanoi

Of the sections of pure mathematics (without going into details) known, that any computable algorithm can be expressed in the form of a recursive formulation. One of the most interesting features of images and the power of recursive computation is the problem of the Tower of Hanoi.

Allegedly, that this problem is formulated and solved still some monks from monasteries in Tibet. The challenge is, to the pyramid of the rings (in the style of children's toys), strung on one of the 3 bars, transfer to another such rod, adhering to strict rules:

    • N pyramid consists of rings of different sizes, descending rings stacked one on another diameter;
    • shift in a single operation can be only one ring from any pin on any ...
    • but only if, that can only be put on top of a smaller ring for more, but not vice versa;
    • necessary, eventually, All original pyramid, lying on the pin №1, move to pin №3, №2 using the pin as an intermediate.

For example, for 2 rings result is such a sequence rearrangements: 1 => 2 , 1 => 3 , 2 => 3

According to legend, the task of passing the N = 10 rings, solve the Tibetan monks, and when it, finally, decide, and then come to an end ... Armageddon, in our Western notation.

For those wishing to exercise special, immediately formulate the task №2: try to solve this problem is not recursive methods (this is a very difficult task)!

Now we write the solution of the problem:

The solution here (if such can be named) It is, if necessary, to transfer the pyramid of n rings from the pin number on the pin with sequence number to make the following:

    • postpone (somehow) smaller pyramid of n-1 rings temporarily pin number with temp, not to interfere…
    • transfer remains the sole bottom (most) ring on the pin with the result to the number
    • then, just as in the first paragraph, hoist the pyramid (n-1 rings) with temp numbers on top of the largest ring to pin to a number.

It is important that, we do not know how, and we are not able to perform the 1 st and 3 rd place in our program, but hope, that he will Recursive unwind by analogy, using the same algorithm, but a smaller number of n-1 (the fundamental principle of recursion)… while n equals 1 – and there is quite simply.

And now unfold solution for different N:

You can run this program for N = 10 (not only provoke the end of the world!) and make sure, that the number of permutations for this need 1023. And generally speaking, for any N is the number of permutations 2**(N – 1), that is a very high degree of growth of the computational complexity of the problem - the exponential.

Leave a Reply

Your email address will not be published. Required fields are marked *