use pointers instead of non-const references and globals

This commit is contained in:
Krishna Vedala 2020-05-28 16:05:43 -04:00
parent e12a5d4b5d
commit b9b930213f
No known key found for this signature in database
GPG Key ID: BA19ACF8FC8792F7

View File

@ -13,21 +13,22 @@ struct tower {
int values[10];
//! top tower ID
int top;
} F, U, T;
};
/** Display the towers */
void show() {
void show(const struct tower *const F, const struct tower *const T,
const struct tower *const U) {
std::cout << "\n\n\tF : ";
for (int i = 0; i < F.top; i++) {
std::cout << F.values[i] << "\t";
for (int i = 0; i < F->top; i++) {
std::cout << F->values[i] << "\t";
}
std::cout << "\n\tU : ";
for (int i = 0; i < U.top; i++) {
std::cout << U.values[i] << "\t";
for (int i = 0; i < U->top; i++) {
std::cout << U->values[i] << "\t";
}
std::cout << "\n\tT : ";
for (int i = 0; i < T.top; i++) {
std::cout << T.values[i] << "\t";
for (int i = 0; i < T->top; i++) {
std::cout << T->values[i] << "\t";
}
}
@ -35,10 +36,10 @@ void show() {
* \param [in,out] From tower to move disk *from*
* \param [in,out] To tower to move disk *to*
*/
void mov(tower &From, tower &To) {
--From.top;
To.values[To.top] = From.values[From.top];
++To.top;
void mov(tower *From, tower *To) {
--From->top;
To->values[To->top] = From->values[From->top];
++To->top;
}
/**
@ -48,20 +49,22 @@ void mov(tower &From, tower &To) {
* \param [in,out] Using temporary tower for the puzzle
* \param [in,out] To tower to move disk to
*/
void TH(int n, tower &From, tower &Using, tower &To) {
void TH(int n, tower *From, tower *Using, tower *To) {
if (n == 1) {
mov(From, To);
show();
show(From, To, Using);
} else {
TH(n - 1, From, To, Using);
mov(From, To);
show();
show(From, To, Using);
TH(n - 1, Using, From, To);
}
}
/** Main function */
int main() {
struct tower F, U, T;
F.top = 0;
U.top = 0;
T.top = 0;
@ -75,8 +78,8 @@ int main() {
F.values[F.top++] = i;
}
show();
TH(no, F, U, T);
show(&F, &T, &U);
TH(no, &F, &U, &T);
return 0;
}