Skip to content

Instantly share code, notes, and snippets.

@linuskmr
Created March 11, 2021 13:56
Show Gist options
  • Save linuskmr/1703a3c49f7cf324e0118302574ab586 to your computer and use it in GitHub Desktop.
Save linuskmr/1703a3c49f7cf324e0118302574ab586 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Must be a multiply of 8
const int TOTAL = 1000000;
int main() {
struct timespec start;
clock_gettime(CLOCK_REALTIME, &start);
// Seed the random generator
srand(time(NULL));
int sum = 0;
// In each iteration of the loop we get 8 random pairs, so we
// run the loop only TOTAL/8 times.
for (int i = 0; i < TOTAL / 8; i++) {
int rand_value = rand();
for (int j = 0; j < 8; j++) {
// Take 4 bit from the random value for 8 times.
// This results in 32 bit which is the size of an int.
// First random value are the lower 2 bits
int r1 = (rand_value & 0b11);
rand_value >>= 2;
// Second random value are the higher 2 bits
int r2 = (rand_value & 0b11);
rand_value >>= 2;
if (r1 == r2) {
sum++;
}
}
sum += rand_value;
}
double probability = (double)sum / TOTAL;
struct timespec end;
clock_gettime(CLOCK_REALTIME, &end);
printf("Probability %f\n", probability);
printf("%lus %fms\n", end.tv_sec-start.tv_sec, (double)(end.tv_nsec - start.tv_nsec)/1e6);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment