I'm a beginner in C. I'm writing a program to demonstrate a random walk in 2D (that is, a point up/down/left/right, y+1, y-1, x-1, x+1 ). I have written a program that randomly generates numbers of up/down/left/right for me, however as I get to the distance travelled calculation part (distance = r = sqrt(x*x+y*y) ), I realise I better off do this with arrays.
I looked up some books and made a start by setting
Code:
int dx[]= { 0, 0, -1, 1 } ;
int dy[]= { -1, 1, 0, 0 } ;
but I am struggling on putting them together, and it is hard to find examples online on that.
Any help or suggestion is appreciated.Attachment 11040
Code:
include <stdio.h>
#include <stdlib.h>
#include <time.h>
int up;
int down;
int left;
int right;
int x = 0;
int y = 0;
int dx[]= { 0, 0, -1, 1 } ;
int dy[]= { -1, 1, 0, 0 } ;
int r;
int flip( void );
int main( void )
{
int toss;
srand(time(NULL));
FILE *out;
out=fopen("data.txt", "w");
for ( toss = 1; toss <= 200; toss++ ){
printf( "%d\n", flip( ));
fprintf(out,"%d\n",flip( ));
if (flip( ) == 0)
up++;
else if (flip( ) == 1)
down++;
else if (flip () == 2)
left++;
else
right++;
}
fclose(out);
printf( "Up had been flipped %d times\n", up );
printf( "Down had been flipped %d times\n", down );
printf( "Left had been flipped %d times\n", left );
printf( "Right had been flipped %d times\n", right );
return 0;
}
int flip( )
{
int i = rand() % 4;
if (i == 0)
return 0;
else if (i == 1)
return 1;
else if (i == 2)
return 2;
else
return 3;
}