- #1
FallenApple
- 566
- 61
1)I have two questions. I don't know why pegs[0].push(i); is used inside the for loop in the first void function. It makes sense that the program needs rings to be placed on a stack. But why pegs[0]? why not pegs[i]?
Mod note: Edited pegs[ i] above to prevent the following text to be rendered as italic.
2) What is the array <stack<int>,kNumPegs>pegs ? Is it a vector? Vectors have that <> symbol. And why is the stack inside? Is it because we need 3 pegs?3)Also, I can't get this to implement in the main. I got this code from my book but they didn't have a main function to test it. So I got a bunch of errors. My C++ is a bit rusty so I don't know what should be done in the main to implement this.
Mod note: Edited pegs[ i] above to prevent the following text to be rendered as italic.
2) What is the array <stack<int>,kNumPegs>pegs ? Is it a vector? Vectors have that <> symbol. And why is the stack inside? Is it because we need 3 pegs?3)Also, I can't get this to implement in the main. I got this code from my book but they didn't have a main function to test it. So I got a bunch of errors. My C++ is a bit rusty so I don't know what should be done in the main to implement this.
Code:
#include <iostream>
using namespace std;
const int kNumPegs=3;
void ComputeTowerHanoi(int num_rings){
array <stack<int>,kNumPegs>pegs; //initialize pegs
for(int i=num_rings; i>=1; --i){
pegs[0].push(i);
}
ComputeTowerHanoiSteps(num_rings,pegs,0,1,2);
}void ComputeTowerHanoiSteps(int num_rings_to_move,array<stack<int>,kNumPegs>&pegs, int from_peg,int to_peg,int use_peg){
if(num_rings_to_move>0){
ComputeTowerHanoiSteps(num_rings_to_move-1,pegs,from_peg,use_peg,to_peg);
pegs[to_peg].push(pegs[from_peg].top());
pegs[from_peg].pop();
cout<<"Move from peg "<<from_peg<<" to peg "<<to_peg<<endl;
ComputeTowerHanoiSteps(num_rings_to_move-1,pegs,use_peg,to_peg,from_peg);
}
}int main() {
ComputeTowerHanoi(3);
}
Last edited by a moderator: