forked from mgechev/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhanoi.js
More file actions
47 lines (44 loc) · 1.31 KB
/
hanoi.js
File metadata and controls
47 lines (44 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
(function (exports) {
'use strict';
/**
* Returns all movements needed to solve Hanoi Tower problem.
*
* @public
* @module others/hanoi
*
* @example
*
* var hanoi = require('path-to-algorithms/src/others/hanoi').hanoi;
* var movements = hanoi(3, 'a', 'b', 'c');
*
* // Move a to c
* // Move a to b
* // Move c to b
* // Move a to c
* // Move b to a
* // Move b to c
* // Move a to c
* movements.forEach(function (move) {
* console.log('Move', move[0], 'to', move[1]);
* });
*
* @param {Number} count Count of the plates/stones.
* @param {String|Number} source Identifier of the 1st peg.
* @param {String|Number} intermediate Identifier of the 2nd peg.
* @param {String|Number} goal Identifier of the 3rd peg.
* @return Array which contains all the moves required
* in order to place all the plates onto the last peg.
*/
function hanoi(count, source, intermediate, goal, result) {
result = result || [];
if (count === 1) {
result.push([source, goal]);
} else {
hanoi(count - 1, source, goal, intermediate, result);
result.push([source, goal]);
hanoi(count - 1, intermediate, source, goal, result);
}
return result;
}
exports.hanoi = hanoi;
})(typeof window === 'undefined' ? module.exports : window);