-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTower of Hanoi.cpp
More file actions
63 lines (49 loc) · 2.1 KB
/
Tower of Hanoi.cpp
File metadata and controls
63 lines (49 loc) · 2.1 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
//Mohammed Chowdhury
//cs 211 - 22C
//Assignment # 13
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> t[3];
int n;
cout << "Please enter the number of rings to move: ";
cin >> n;
cout << endl;
// The initial value of "to" depends on whether n is odd or even
int from = 0, to , candidate = 1, move = 0;
if (n%2 == 0) to = (from +2) %3;// if n is even, go left
else to = (from +1) %3; //if n is odd, go right
// Initialize the towers
for(int i = n + 1; i >= 1; --i)
t[0].push_back(i); // puts all the n + 1 rings on tower 0
t[1].push_back(n+1); //puts the 1 bigger than biggest ring in tower 1
t[2].push_back(n+1); // puts the 1 bigger than biggest ring in tower 2 as well.
while (t[1].size() < n+1) { // while t[1] does not contain all of the rings
cout << "Move #" << ++move << ": Transfer ring " << candidate << " from tower " << char(from+'A') << " to tower " << char(to+'A') << "\n";
// Move the ring from the "from tower" to the "to tower" (first copy it, then delete it from the "from tower")
t[to].push_back(t[from].back()); //take the top ring from "from" tower and puts in on "to" tower
t[from].pop_back();//deletes that ring from the "from" tower after transferring it.
// from = the index of the tower with the smallest ring that has not just been moved: (to+1)%3 or (to+2)%3
if (t[(to+1) % 3].back() < t[(to+2) % 3].back())
from = (to+1) % 3;
else
from = (to+2) % 3;
// candidate = the ring on top of the t[from] tower
candidate = t[from].back();
// to = the index of the closest tower on which the candidate can be placed: (from+1)%3 or (from+2)%3
// (compare the candidate with the ring on the closer tower; which tower is "closer" depends on whether n is odd or even)
if ((n%2) !=0) {
if (t[(from+1) % 3].back() > candidate)
to = (from+1)%3;
else
to = (from+2)%3;
}
else
if(t[(from+2) % 3].back() > candidate)
to = (from+2) % 3;
else
to = (from+1) % 3;
}
return 0;
}