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