I'm having a decent amount of trouble implementing the optimal algorithm for the tower of hanoi game for four stools in python.
First, in class we solved the tower of hanoi algorithm for three towers, for which we were given the following algorithm:
- Move all but the bottom disk from source to intermediate tower
- Move the bottom disk form the source to the destination
- Move all but the bottom disk from intermediate stool to destination tower
The actual code for this algorithm (with model being of class Model which has towers and disks, with a move method that moves disks from one tower to another) yields:
def move_disks(n, source, intermediate, destination):
"""Move n disks from source to destination
@param int n:
@param int source:
@param int intermediate:
@param int destination:
@rtype: None
"""
if n > 1:
move_disks(n - 1, source, destination, intermediate)
move_disks(1, source, intermediate, destination)
move_disks(n - 1, intermediate, source, destination)
else:
model.move(source, destination)
Now for four stools, I'm given the following:
- Move n- i disks to intermediate stool using all four towers
- Move i disks from the original tower to the destination tower, using only three available towers
- Move n-i smallest disks from intermediate tower to destination tower
Manually playing around with disks and towers I got n-i = 2 if n>=3 and i = 1 if n =2. Since there are 4 possible sources and destinations, in my own function I have 5 arguments instead of 4:
def move_disks(n, source, intermediate, intermediate2, destination):
"""Move n disks from source to destination
@param int n:
@param int source:
@param int intermediate:
@param int intermediate2:
@param int destination:
@rtype: None
"""
if n > 1:
move_disks(n - i, source, intermediate 2 destination, intermediate)
move_disks(1, source, intermediate, intermediate2, destination)
move_disks(n - i, intermediate, intermediate2, source, destination)
else:
print("{} -> {}".format(source,destination)) # used to explicitly follow output in the console
#model.move(source, destination) --> to be implemented when the function returns the right output
When I run it for n=3 I get:
1 -> 3
1 -> 2
3 -> 2
1 -> 4
2 -> 3
2 -> 4
3 -> 4
which gives the same number as moves as the solution for three towers. The optimal solution for four stools should yield:
1 -> 3
1 -> 2
1 -> 4
2 -> 4
3 -> 4
The problem is definitely coming from my understanding of the algorithm so I've tried tracing function calls on a dry erasable board for a few hours to no avail.
Any tips or tricks for what else I should be doing or looking for to solve this algorithm? I'm honestly lost and a little bit discouraged.
source
,intermediate
and following parameters? They're used nowhere in the code except as parameters for the recursive calls in both provided code-snippets. – Pauln
are just labels for the towers. The recursion is happening onn
(with the others parameters merely getting rearranged). – Blckknght