Back to Freecodecamp

Step 50

curriculum/challenges/english/blocks/learn-recursion-by-solving-the-tower-of-hanoi-puzzle/64df496c6a8ddf1b38db1ed6.md

latest1.3 KB
Original Source

--description--

In a previous step, you wrote the code to move the largest disk of the sub-problem to the target rod.

Now, all you need to do is add another recursive call to move the n - 1 disks you have already displaced. Copy the first recursive call and paste it at the end of the if block.

Note that the function arguments are not in the right order. Try to figure out the correct order.

--hints--

You should call move(n - 1, auxiliary, source, target) at the end of your move function.

js
({ test: () => assert.match(code, /^\s{8}move\(\s*n\s*-\s*1\s*,\s*auxiliary\s*,\s*source\s*,\s*target\s*\)/m) })

--seed--

--seed-contents--

py
NUMBER_OF_DISKS = 4
rods = {
    'A': list(range(NUMBER_OF_DISKS, 0, -1)),
    'B': [],
    'C': []
}

--fcc-editable-region--
def move(n, source, auxiliary, target):
    if n > 0:
        # move n - 1 disks from source to auxiliary, so they are out of the way
        move(n - 1, source, target, auxiliary)
        
        # move the nth disk from source to target
        rods[target].append(rods[source].pop())
        
        # display our progress
        print(rods, '\n')
              
--fcc-editable-region--
# initiate call from source A to target C with auxiliary B
move(NUMBER_OF_DISKS, 'A', 'B', 'C')