|
ADS
Algorithms and Data Structures
|
The towers of Hanoi: moving \( n \) disks from the peg source to the peg dest, one at a time and never on a smaller one, with the peg middle as a spare. More...
#include "ADS/Contract.h"#include "ADS/stack/ArrayStack.h"#include <tuple>#include <utility>#include "ADS/algorithm/impl/Hanoi.tpp"Go to the source code of this file.
Namespaces | |
| namespace | ADS |
Functions | |
| template<class F> | |
| void | ADS::hanoi_recursive (int n, int source, int dest, int middle, F &&f) |
| the moves of \( n \ge 1 \) disks from source to dest, by the recursion of the book (its hanoi-recursive()) | |
| template<class F> | |
| void | ADS::hanoi_iterative (int n, int source, int dest, int middle, F &&f) |
| the moves of hanoi_recursive() with the calls on a stack (the first hanoi-iterative() of the book): the calls (1) are pushed, and each pop resumes the call left open, moving a disk and simulating the call (2) | |
| template<class F> | |
| void | ADS::hanoi_iterative_labels (int n, int source, int dest, int middle, F &&f) |
| the moves of hanoi_recursive() by the systematic rules (the second hanoi-iterative() of the book), saving on the stack the parameters and the label from which the call resumes | |
The towers of Hanoi: moving \( n \) disks from the peg source to the peg dest, one at a time and never on a smaller one, with the peg middle as a spare.
The recursive procedure moves \( n - 1 \) disks on middle, the last one on dest and the \( n - 1 \) disks on dest, hence it makes
\[ T( n ) = 2 T( n - 1 ) + 1 = 2^n - 1 \]
moves. The two iterative procedures of the book simulate its calls with a STACK of their parameters: the first one by hand, the second one by the systematic rules that also save the point where a call resumes (START, AFTER1, END, STOP). All of them hand each move to a function f( from , to ), so that the sequence of moves can be checked.
The contracts [see Contract.h]: \( n \ge 1 \) disks and three distinct pegs. The functions are defined in Hanoi.tpp.