Skip to content

Commit 5a55b15

Browse files
committed
Added Tower of Hanoi
1 parent af0b0bb commit 5a55b15

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

‎OtherAlgorithms/Algorithms_toDo.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,4 @@
33
+ anagrams
44
+ word patterns
55
+ game of life
6-
+ password generator
7-
+ tower of hanoi
6+
+ password generator

‎OtherAlgorithms/towerofhanoi.js‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
function toh(count, source, aux, destination, steps) {
2+
3+
steps = steps || [];
4+
5+
// if only one disc remains transfering it from source to destination
6+
if (count === 1) {
7+
steps.push({
8+
'disc': 1,
9+
'from': source,
10+
'to': destination
11+
});
12+
}
13+
else {
14+
//aux becomes destination and destination becomes aux
15+
hanoi(count - 1, source, destination, aux, steps);
16+
17+
steps.push({
18+
'disc': count,
19+
'from': source,
20+
'to': destination
21+
});
22+
23+
// aux become source and source become aux
24+
hanoi(count - 1, aux, source, destination, steps);
25+
}
26+
return steps;
27+
}
28+
29+
// X: Source Y: Auxiliary Z: Destination
30+
var steps = toh(5,'X','Y','Z');
31+
32+
steps.forEach((step)=>
33+
console.log(step.disc+' moved from '+step.from+' to '+step.to)
34+
);

0 commit comments

Comments
 (0)