Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
circular-random/circular-random.c
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
75 lines (65 sloc)
1.62 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int direction() | |
{ | |
//Generate a random number to determine the direciton of the next step | |
if(rand()%2 == 0) return -1; | |
else return 1; | |
} | |
//Implement the following function | |
//The random walker starts from 0. | |
//At every step, the walker can go to clockwise direction if the direction() functions returns 1 | |
//or go to counter-clockwise direciton if the direction() function returns -1 | |
//The function returns after the walker returns to 0. | |
//The return value of the function is the number of steps taken until the walker returns to 0 | |
int circular_random_walk(int k) | |
{ | |
//Fill in your code below | |
int steps = 0; | |
int location = 0; | |
do { | |
int direct = direction(); | |
if((direct == -1) && (location == 0)){ | |
location = k - 1; | |
steps++; | |
} | |
else if((direct == 1) && (location == k - 1)){ | |
location = 0; | |
steps++; | |
} | |
else if(direct == 1) | |
{ | |
location++; | |
steps++; | |
} | |
else | |
{ | |
location--; | |
steps++; | |
} | |
} while((location != k) && (location != 0) && (location != -k)); | |
return steps; | |
} | |
//Do not change the following code. | |
int main() | |
{ | |
int i; | |
double sum; | |
int steps; | |
//Set the seed of the random number generator to 12345 | |
srand(12345); | |
int k; | |
printf("Enter k: "); | |
scanf("%d", &k); | |
sum = 0.; | |
int n = 1000000; | |
int max = 0; | |
for(i=1; i<= n; i++) | |
{ | |
steps = circular_random_walk(k); | |
sum += steps; | |
if(steps > max) max = steps; | |
} | |
printf("average=%.3lf, max = %d \n", sum/n, max); | |
return 0; | |
} |