Created
October 26, 2021 03:10
-
-
Save louisswarren/90d558644855a6c23bf89330d0301e18 to your computer and use it in GitHub Desktop.
Roll dice for a while in C
This file contains hidden or 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> | |
#include <time.h> | |
unsigned long long counts[6] = {0}; | |
unsigned long long trials = 0; | |
void | |
roll_dice(void) | |
{ | |
/* Does not check for overflows. If you think you're going to do more | |
* than ULLONG_MAX trials, it's your responsibility to check! */ | |
int rmax = RAND_MAX >> 3; | |
int r = rand(); | |
do { | |
counts[r & 7] += !((r & 6) == 6); | |
trials += !((r & 6) == 6); | |
r >>= 3; | |
rmax >>= 3; | |
} while (rmax); | |
} | |
void | |
print_table(void) | |
{ | |
int i; | |
printf("%llu trials:\n", trials); | |
for (i = 0; i < 6; ++i) { | |
printf("%d: %llu (%0.4f)\n", | |
i, counts[i], (float) counts[i] / trials); | |
} | |
} | |
void | |
trial_time(int runtime) | |
{ | |
int trials_per_grain; | |
int i; | |
unsigned long long start_trials = trials; | |
clock_t start_clock = clock(); | |
/* Run initially for 10ms, then approximate time target time at 10ms | |
* granularity. This is much faster than checking the clock every | |
* iteration. */ | |
while (clock() - start_clock < CLOCKS_PER_SEC / 100) | |
roll_dice(); | |
trials_per_grain = trials - start_trials; | |
while (clock() - start_clock < CLOCKS_PER_SEC * runtime) { | |
for (i = 0; i < trials_per_grain; ++i) | |
roll_dice(); | |
} | |
} | |
int | |
main(void) | |
{ | |
trial_time(1); | |
print_table(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment