Skip to content

Commit fe5f225

Browse files
committed
Tower of Hanoi ES6 solution added
1 parent d1e74f4 commit fe5f225

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

Others/Tower of Hanoi/es6/test.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
const Hanoi = require('./tower_of_hanoi')
2+
3+
/****** Testing Tower of Hanoi code *******/
4+
Hanoi(3, 'A', 'B', 'C').forEach((move) => console.log(`moved ${move.disk} from: ${move.from} to: ${move.to}`))
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/* Tower of Hanoi implementation in Javascript(ES6) */
2+
3+
// This function will recursively store all the moves and return the moves information as Array
4+
const hanoi = (count, source, aux, destination, moves) => {
5+
moves = moves || [];
6+
7+
// When there is only single disk move it from 'source' to 'destination'
8+
if (count === 1) {
9+
moves.push({
10+
'disk': 1,
11+
'from': source,
12+
'to': destination
13+
});
14+
}
15+
else {
16+
// Move 'n-1' disks from 'source' to 'aux'
17+
hanoi(count - 1, source, destination, aux, moves);
18+
19+
// Move n-th disk from 'source' to 'detination'
20+
moves.push({
21+
'disk': count,
22+
'from': source,
23+
'to': destination
24+
});
25+
26+
// Move (n-1) disks from 'aux' to 'destination'
27+
hanoi(count - 1, aux, source, destination, moves);
28+
}
29+
return moves;
30+
}
31+
32+
module.exports = hanoi

0 commit comments

Comments
 (0)