id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

towerOfHanoi


The Tower of Hanoi is a puzzle where there is a stack of disks, each one smaller than the one below it, all placed on one of three rods. The puzzle is to move all the disks from the left rod to the right rod, possibly using the middle rod as necessary. You can only move one disk at a time, onto another rod, but never moving a disk onto a disk that is smaller.

For this problem, you are given lists of the rods that can contain disks, but you must solve this question by converting them to stacks and using push and pop. The rod names are "L" for left, "M" for middle, and "R" for right. The parameters 3, [3,2,1], [], [] means to move the pile of 3 disks from the L rod to the R rod, using the M rod if necessary.

The function should return a String array containing the moves required, where each move is represented as a string of the form "1LM", which means to move disk number 1 from the left to the middle rod.

Start out with the following code:

Stack<Integer> left = new Stack<Integer>(); left.addAll(L);
Stack<Integer> middle = new Stack<Integer>(); middle.addAll(M);
Stack<Integer> right = new Stack<Integer>(); right.addAll(R);

towerOfHanoi(1, [1], [], []) → ["1LR"]
towerOfHanoi(2, [2, 1], [], []) → ["1LM", "2LR", "1MR"]
towerOfHanoi(3, [3, 2, 1], [], []) → ["1LR", "2LM", "1RM", "3LR", "1ML", "2MR", "1LR"]

...Save, Compile, Run (ctrl-enter)

public String[] towerOfHanoi(int numDisks, List<Integer> L, List<Integer> M, List<Integer> R){ }

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Java Help

Misc Code Practice

Post-solution available

Copyright Nick Parlante 2017 - privacy