Dear all,

PLEASE READ THE QUESTION AND SEE IF YOU CAN FIGURE OUT WHY MY PROGRAM QUITS!

Suppose you got yourself drunk after a night out and you are about to go home. You

are so intoxicated that for every step you take there is an equal probability that you

either move forward by one step, or move backward by one step. Assuming that you

are at the starting position 0. If you are allowed to take exactly one step, then you

either end at at positions +1 or −1. If you are allowed exactly two steps starting at

position 0, then you either ˆ end up at positions −2: Take two steps back. ˆ 0: One step forward, followed by one step back; or one step backward, followed

by one step forward. ˆ +2. Take two steps forward.

If you are allowed exactly three steps, then you end up at positions −3, −1, 1 or 3.

In general, if you are allowed to take n steps, you would end up at n + 1 different

positions. Moreover, you will always end up in odd positions if n is odd, and even

positions if n is even.

: The getDrunk function simply performs the walk and moves forwards or backwards

without regards to whether it is out of the bounds of the array. At the end of

every trial, increment the final position by one. Every trial should begin at the

same starting location. In the main function, you have to ensure that getDrunk

receives the correct starting position in the array, such that the walk will always

be within the array.

Code:

#include <stdio.h>
#include <stdlib.h>
void readValues(int *numTrials,int *numSteps);
void getDrunk(int *path,int numTrials,int numSteps);
void printPath(int path[],int size);
int main()
{
int numTrials,numSteps;
int path[30] = {0};
srand(123); // printf("%d\n",rand());
readValues(&numTrials,&numSteps); //printf("%d %d\n",numTrials,numSteps);
getDrunk(&(path[15]),numTrials,numSteps);
//printPath(path,15);
system("pause > null");
return 0;
}
void readValues(int *numTrials,int *numSteps)
{
printf("Enter the num of trials and steps(strictly <= 15 )\n");
scanf("%d%d",numTrials,numSteps);
return;
}
void getDrunk(int *path,int numTrials,int numSteps)
{
int i,steps,dir;
for(i=0;i<numTrials;i++)
{
steps = rand() % numSteps;
dir = rand() % 2; // 0 is back and 1 is forward
if(numSteps % 2 == 0) // even
{
if(steps % 2 != 0)
steps = steps + 1;
if(dir == 0)
{
path = path - steps;
*path = *path + 1;
}
else
{
path = path + steps;
*path = *path + 1;
}
}
else // odd
{
if(steps % 2 == 0)
steps = steps + 1;
if(dir == 0)
{
path = path - steps; // move back
*path = *path + 1;
}
else
{
path = path + steps;
*path = *path + 1;
}
}
path = &(path[15]); // reset back to centre
}
return;
}
void printPath(int path[],int size)
{
int i;
for(i=0;i<30;i++);
{
printf(" %d: ");
if(path[i] > 0)
{
printf("%d ",path[i]);
}
}
return;
}