One Move from Towers of Hanoi
InterviewTime limit3sMemory limit128 MB
Given n disks and an index k, report the disk and the source and destination posts of the kth move in the classic recursive Hanoi solution.
- Level
Medium5 of 10
- Topics
- Recursion, Bit manipulation, Math
- Solved
- No attempts yet
Problem
This problem is about the classic Towers of Hanoi. There are three posts and a collection of circular disks. Call the number of disks . The disks have different sizes, with no two sharing a radius, and there is one rule: never put a bigger disk on top of a smaller one. Number the disks from 1 (smallest) to (biggest) and name the posts A, B, and C. All the disks start on post A, and the goal is to move them to post C one at a time, again never putting a bigger one on top of a smaller one. The well-known solution recursively moves the top disks from A to B, moves the bottom disk from A to C directly, then recursively moves those disks from B to C.
Pseudocode for a recursive solution to the classic Towers of Hanoi problem:
move(num_disks, from_post, spare_post, to_post)
if (num_disks == 0)
return
move(num_disks - 1, from_post, to_post, spare_post)
print ("Move disk ", num_disks, " from ",
from_post, " to ", to_post)
move(num_disks - 1, spare_post, from_post, to_post)
Given and , determine the th move made by the algorithm above.
Input
Each line of input holds two integers and . A line with two zeros marks the end of input.
All input is valid. and are positive integers, so that a th move exists, and so that the answer fits in a 64-bit integer type.
Output
For each test case, print the th move made by the algorithm above. Follow this format exactly: Case, one space, the case number, a colon and one space, then the answer for that case given as the number of the disk, the name of the from_post, and the name of the to_post, with one space separating the parts of the answer. Do not print any trailing spaces.