-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhanoi.js
More file actions
44 lines (37 loc) · 805 Bytes
/
hanoi.js
File metadata and controls
44 lines (37 loc) · 805 Bytes
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
if (typeof window === 'undefined') {
util = require(__dirname + '/../util.js');
}
class Stack {
constructor() {
this.container = [];
}
push(item) {
this.container.push(item);
}
pop(item) {
return this.container.pop();
}
toString() {
return this.container.join(', ');
}
}
let numDiscs = 3;
let towerA = new Stack();
let towerB = new Stack();
let towerC = new Stack();
for (let i = 1; i <= numDiscs; i++) {
towerA.push(i);
}
function hanoi(begin, end, temp, n) {
if (n == 1) {
end.push(begin.pop());
} else {
hanoi(begin, temp, end, n - 1);
hanoi(begin, end, temp, 1);
hanoi(temp, end, begin, n - 1);
}
}
hanoi(towerA, towerC, towerB, numDiscs);
util.out('Tower A: ' + towerA);
util.out('Tower B: ' + towerB);
util.out('Tower C: ' + towerC);