#include #include #include #include #include using Towers = std::array, 3>; // Plays the one legal move between towers a and b, whichever way round it goes. void move_between(Towers& towers, int a, int b) { if (towers[a].empty() || (!towers[b].empty() && towers[b].back() < towers[a].back())) { std::swap(a, b); } int disk = towers[a].back(); towers[a].pop_back(); towers[b].push_back(disk); std::cout << "Move disk " << disk << " from " << "ABC"[a] << " to " << "ABC"[b] << '\n'; } void hanoi_pairs(int n) { Towers towers; for (int disk = n; disk >= 1; disk--) { towers[0].push_back(disk); } // The same three pairs of towers, over and over. For an odd n, B and C trade places. const int b = n % 2 == 0 ? 1 : 2; const int c = 3 - b; const std::uint64_t total = (std::uint64_t{1} << n) - 1; for (std::uint64_t m = 0; m < total; m++) { switch (m % 3) { case 0: move_between(towers, 0, b); break; case 1: move_between(towers, 0, c); break; case 2: move_between(towers, b, c); break; } } } int main() { hanoi_pairs(3); }