3.1 KiB
3.1 KiB
title | id | challengeType |
---|---|---|
Towers of Hanoi | 5951ed8945deab770972ae56 | 5 |
Description
Solve the Towers of Hanoi problem.
Your solution should accept the number of discs as the first parameters, and
three string used to identify each of the three stacks of discs, for example
towerOfHanoi(4, 'A', 'B', 'C')
. The function should return an
array of arrays containing the list of moves, source -> destination. For
example, the array [['A', 'C'], ['B', 'A']]
indicates that the
1st move was to move a disc from stack A to C, and the 2nd move was to move a
disc from stack B to A.
Instructions
Tests
tests:
- text: <code>towerOfHanoi</code> is a function.
testString: assert(typeof towerOfHanoi === 'function', '<code>towerOfHanoi</code> is a function.');
- text: <code>towerOfHanoi(3, ...)</code> should return 7 moves.
testString: assert(res3.length === 7, '<code>towerOfHanoi(3, ...)</code> should return 7 moves.');
- text: <code>towerOfHanoi(3, 'A', 'B', 'C')</code> should return <code>[['A','B'],['A','C'],['B','C'],['A','B'],['C','A'],['C','B'],['A','B']]</code>
testString: assert.deepEqual(towerOfHanoi(3, 'A', 'B', 'C'), res3Moves, "<code>towerOfHanoi(3, 'A', 'B', 'C')</code> should return [['A','B'],['A','C'],['B','C'],['A','B'],['C','A'],['C','B'],['A','B']].");
- text: <code>towerOfHanoi(5, "X", "Y", "Z")</code> 10th move should be Y -> X.
testString: assert.deepEqual(res5[9], ['Y', 'X'], '<code>towerOfHanoi(5, "X", "Y", "Z")</code> 10th move should be Y -> X.');
- text: <code>towerOfHanoi(7, 'A', 'B', 'C')</code> first ten moves are <code>[['A','B'],['A','C'],['B','C'],['A','B'],['C','A'],['C','B'],['A','B'],['A','C'],['B','C'],['B','A']]</code>
testString: assert.deepEqual(towerOfHanoi(7, 'A', 'B', 'C').slice(0, 10), res7First10Moves, "<code>towerOfHanoi(7, 'A', 'B', 'C')</code> first ten moves are [['A','B'],['A','C'],['B','C'],['A','B'],['C','A'],['C','B'],['A','B'],['A','C'],['B','C'],['B','A']].");
Challenge Seed
function towerOfHanoi (n, a, b, c) {
// Good luck!
return [[]];
}
After Test
const res3 = towerOfHanoi(3, 'A', 'B', 'C');
const res3Moves = [['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B'], ['C', 'A'], ['C', 'B'], ['A', 'B']];
const res5 = towerOfHanoi(5, 'X', 'Y', 'Z');
const res7First10Moves = [['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B'], ['C', 'A'], ['C', 'B'], ['A', 'B'], ['A', 'C'], ['B', 'C'], ['B', 'A']];
Solution
function towerOfHanoi(n, a, b, c) {
const res = [];
towerOfHanoiHelper(n, a, c, b, res);
return res;
}
function towerOfHanoiHelper(n, a, b, c, res) {
if (n > 0) {
towerOfHanoiHelper(n - 1, a, c, b, res);
res.push([a, c]);
towerOfHanoiHelper(n - 1, b, a, c, res);
}
}