Your question ruined my productivity!
I just spent my precious time trying to answer it, and here is the result:
First you need to figure out the place where each drive wants to go, from the largest to the smallest. There are 3 simple rules:
- The largest drive wants to go right.
- If a disk with a large number of disks moves, the disk wants to "get out of the way" (if
N+1 wants to switch from LEFT to MIDDLE , then N wants to go to RIGHT ). - If a disk with a large volume does not move, the disk wants to go to the same place (if
N+1 remains in RIGHT , N wants to go to RIGHT ).
Then it will move to the right place on the smallest disk that does not want to remain mated . (edit: as an alternative, you can transfer the first disk you encounter that wants to make a legal move, but that means your code has an idea of ββwhat the legal move is)
Iterate until it decides.
Example
Take Justin's example.
Starting tower
| | | | | | | | | | 1 | 4 2 | 6 5 3
6 want to switch from LEFT to RIGHT (rule 1).5 want to switch from CENTER to CENTER (rule 2).4 want to switch from LEFT to CENTER (rule 3).3 want to switch from RIGHT to RIGHT (rule 2).2 want to switch from CENTER to RIGHT (rule 3).1 want to switch from CENTER to LEFT (rule 2).
The first step should be to place disk 1 on the left pointer (the smallest disk that does not want to stay in place).
Further
The following steps will look like this:
| | | | | | | | | 1 | | 4 2 | 6 5 3 | | | | | | | | | 1 | | 4 | 2 6 5 3 | | | | | | | | | | | 1 4 | 2 6 5 3 | | | | | | | | | | | 1 | 4 2 6 5 3 | | | | | | | | | | 1 | | 4 2 6 5 3 | | | | | | | | | | 1 | 2 4 | 6 5 3 etc. // TODO : commenting
I implemented these rules, they work for any initial tower (including the usual all-left tower). In addition, they always take the shortest path.
YAY! A non-recursive way to solve the tower of Hanoi!
source share