-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHanoi_Towers.cpp
More file actions
66 lines (56 loc) · 2 KB
/
Hanoi_Towers.cpp
File metadata and controls
66 lines (56 loc) · 2 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
The program is based on a game of three (3) towers with N number of rings.
The rings are different sizes with the biggest at the bottom and smallest on top.
The user is asked to input the number of rings and program then takes that number
and outputs the best solution to move the rings from one side to the other
(when moving the rings, the big rings cannot go on top of the small rings).
*/
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> t[3]; // three towers A,B,C represented as an array of 3 vectors
int n, candidate,to, from, move=0; // n stands for the number of rings and move counts the move number
cout<<"Please enter a number of rings to move: ";
cin>>n;
cout<<endl;
//intitialize the 3 towers
for(int i=n+1;i>=1;i--)
t[0].push_back(i);
t[1].push_back(n+1);
t[2].push_back(n+1);
// initialize towers and candidate
if((n%2)!=0){
from=0;
to=1;
candidate=1;
}
else{
from=0;
to=2;
candidate=1;
}
while(t[1].size()<n+1){ // there are still rings to transfer to tower B = t[1]
cout<<"move number "<<++move<<": Transfer ring "<<candidate<<
" from tower "<< char(from+65)<<" to tower "<<char(to+65)<<endl;
t[to].push_back(t[from].back());
t[from].pop_back();
//from tower = tower with candidate; smallest available ring which was not just moved
//tower with the just-moved ring is the current to tower
if(t[(to+1)%3].back()<t[(to+2)%3].back()) from=(to+1)%3;
else from=(to+2)%3;
//odd number of rings
if((n%2)!=0){
//"to" = closest tower on which the ring can be placed
if(t[from].back()<t[(from+1)%3].back()) to=(from+1)%3;
else to=(from+2)%3;
}
//even number of rings
else{
if(t[from].back()<t[(from+2)%3].back()) to=(from+2)%3;
else to=(from+1)%3;
}
candidate=t[from].back();
}
return 0;
}