mardi 9 octobre 2018

How to implement a random walk in C?

I'm trying to make a program that simulates a fly caught in a spider's web, it has a certain number of moves to make before its caught or escapes. The way its supposed to work is that each move is a random distance in the range of zero to five centimeters, in a random direction from 0 to 360 degrees.

I'm supposed to initialize the program by setting the X Y coordinates of the fly at (0,0) and the current distance from the center to zero. I then have to initialize a random number generator (srand() and the current time which would be time(0)). I'm then supposed to ask the user for the max number of moves. Then the main loop iterates until max moves have been reached or the distance from the center exceeds the web radius (which would mean the fly escapes). Each iteration of the loop is supposed to pick a random distance of up to 5.0 cm and a random direction of 0 to 360 degrees. From these random values, the change in X and Y is supposed to be calculated and added to the current X and Y position. After the loop terminates, it's supposed to determine whether or not the fly escaped. This program would also require a method to convert polar coordinates to rectangular ones and a method that returns a random double.

/* return random double [0.0, 1.0) */
double randDouble();
/* convert input polar coordinates to output rectangular coordinates */
void polarToRect( double radius, double theta, double *x, double *y );

This is what I have so far:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()

double x,y,distancefromzero;
int moves, webRadius;
x = 0;
y = 0;
distancefromzero = 0;
webRadius = 10;

printf("Enter a max number of moves: \n");
scanf("%d", &moves);

srand(time(0)); 

for(int i = 0; i<= moves; i++) 


return 0; 



double randDouble()
{
  return (double)rand()/((double)RAND_MAX+1);
}

const int limit = 100 ;

int main(int argc, char *argv[])
{
  int j=0 ;
  double r;
  srand( time(NULL) );

  for ( j=0; j < limit; j++ )
  {
    r = randDouble() ;
    printf(" %12.10lf", r );
    if ( j%5 == 4 ) printf("\n");
  }

  printf("\n");
  system("pause");  
  return 0;
}




Aucun commentaire:

Enregistrer un commentaire