Skip to content

Commit 0cc3c84

Browse files
Merge pull request #515 from terodox/master
Add towers of hanoi solution in javascript
2 parents 82b2d3f + 90d0b24 commit 0cc3c84

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

Math/TowerofHanoi/towers-of-hanoi.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
'use strict';
2+
3+
function solveHanoi(height, srcP, desP, bufferP) {
4+
if (height >= 1) {
5+
// Move a tower of height-1 to the buffer peg, using the destination peg.
6+
solveHanoi(height - 1, srcP, bufferP, desP);
7+
// Move the remaining disk to the destination peg.
8+
console.log('Move disk from Tower ', srcP, ' to Tower ', desP);
9+
// Move the tower of `height-1` from the `buffer peg` to the `destination peg` using the `source peg`.
10+
solveHanoi(height - 1, bufferP, desP, srcP);
11+
}
12+
return;
13+
}
14+
15+
solveHanoi(3, "A", "C", "B");

0 commit comments

Comments
 (0)