I am trying to develop a random walk simulation in one dimension. I am modelling a particle along a line with 10 discrete positions that particle can occupy. The particle can only move left or right one space each time it 'hops'. In this simulation I get the code to account for 20 hops. A random number generator produces a 0 - for left and 1 - for right before each 'hop' is executed to tell the "particle" to go left or right. Please see code below and further comments.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int randomInt( int max); // declaration of function //
int main()
{ // declaration of variables //
int i, j = 0;
int totalHops=20;
int seed;
int sites[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *location;
location = &sites[j];
seed = time(NULL);
printf("The seed value for this 'random walk' is: %d.\n\n", seed); //keeping track of the seed used//
// setup the random number generator //
srandom(seed); // random path sequence //
printf("Initial location of the particle is at site %d.\n\n", *location);
for ( i=1; i<totalHops+1; i++ )
{
int direction = randomInt(2); // Two possible directions for particle to move, 0 = left, 1 = right //
if (direction == 1) {
location+= 1; // pointer moves right one space on array //
}
else {
location-= 1; // pointer moves left one space on array //
}
printf("After %2.d hop(s), the particle is at site %d.\n", i, (*location)%10); // I would prefer to be printing the entry of my array rather than relying on the fact the array is lablled with each entry the positon I have changed the pointer to //
}
printf("\n");
}
// function definition //
int randomInt(int max)
{
return (random() % max);
}
My output does not follow each time the sort of patterns I am expecting. It appears to output that the particle is in postion 0 in one iteration and in the next all of a sudden be in postion 4, as an example. I would prefer that I were printing the entry of the sites[] array instead of inputing the postion into each entry and printing the value of the pointer.
I would be most grateful for anyones help here. I am new to pointers so any help would be much appreciated.