Write a program that prompts the users for a walk length and performs 10 random
ID: 3672789 • Letter: W
Question
Write a program that prompts the users for a walk length and performs 10 random walks of the request length And the output should same as this picture with random 10walkQuestion3 A random walk can be thought of as starting at the origin (0) at time t = 0 seconds, and each second thereafter taking either a step to the right (+1) or a step to the left (-1) (each with probability 1/2) for a total walk length of cSteps seconds. Write a program that prompts the user for a walk length cSteps (a positive integer) and performs 10 random walks of the requested length. *For each walk, it should "draw" the position of the walker after each step and should print the final position of the walker after the walk. *It should also print the average ending position over all 10 walks. ECE 114 Lab 8- Bit Operators and Random Numbers 4
Explanation / Answer
Please find the required program below :
#include <time.h> // So we can use time() function
#include <iostream>
#include <string>
using namespace std;
int t = 234;
int GetStep(){
srand (t++); //Randomize seed initialization
int r = rand();
// cout << "random: " <<r << endl;
int randNum = r % 2; // Generate a random number between 0 and 1
if(randNum)
return 1;
else
return -1;
}
void DrawPosition(int currentPosition, int cSteps){
for(int i=0; i<=cSteps; i++){
if(i!=currentPosition)
cout << "-" << flush;
else
cout << "x" << flush;
}
cout << "" << endl;
}
int TakeARandomWalk(int cSteps){
int cPos = 0, i=0;
while(i < cSteps){
int nextStep = GetStep();
cPos = cPos + nextStep;
DrawPosition(cPos,cSteps);
i++;
}
return cPos;
}
int main()
{
int cSteps;
cout << "Enter the cSteps :";
cin >> cSteps;
int cPos, i=0, sum=0;
while(i<10){
cout << "Walk "<< i << endl;
cPos = TakeARandomWalk(cSteps);
cout << "Ended at position " << cPos <<endl;
sum = sum+cPos;
i++;
}
cout << "Average ending position over 10 walks is :" << (sum/10) <<endl;
}