Skip to content

Instantly share code, notes, and snippets.

@skeeto
Created July 7, 2022 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skeeto/1a73f78970755f794c4349eaf05dc7f8 to your computer and use it in GitHub Desktop.
Save skeeto/1a73f78970755f794c4349eaf05dc7f8 to your computer and use it in GitHub Desktop.
Horse racing board game (Monte Carlo method analysis)
// Horse racing board game (Monte Carlo method analysis)
// $ cc -O3 -fopenmp -o race race.c
// $ ./race
// Ref: https://possiblywrong.wordpress.com/2022/07/07/analysis-of-horse-racing-board-game/
// This is free and unencumbered software released into the public domain.
#include <stdio.h>
#include <stdint.h>
#define BAR \
"########################################################################"
static int
r2d6(uint64_t *s)
{
uint32_t r;
do r = (*s = *s*0x3243f6a8885a308d + 1) >> 32;
while (r > (UINT32_C(0xffffffff) - 4)); // eliminate bias
return "CDDEEEFFFFGGGGGHHHHHHIIIIIJJJJKKKLLM"[r%36] - 'A';
}
static uint64_t
hash(int32_t i)
{
uint64_t h = i;
h += 1111111111111111111; h ^= h >> 33;
h *= 1111111111111111111; h ^= h >> 33;
return h;
}
int
main(void)
{
static int curve[] = {
#if 0
2,3,4,5,6,7,6,5,4,3,2
#else
3,6,8,11,14,17,14,11,8,6,3
#endif
};
int32_t n = 1L<<24, hist[11] = {0};
#pragma omp parallel for reduction(+:hist)
for (int32_t i = 0; i < n; i++) {
int horse[11] = {0};
for (uint64_t s = hash(i);;) {
int r = r2d6(&s);
if (++horse[r-2] == curve[r-2]) {
hist[r-2]++;
break;
}
}
}
int maxi = 0;
for (int i = 1; i < 11; i++) {
maxi = hist[i] > hist[maxi] ? i : maxi;
}
for (int i = 0; i < 11; i++) {
int len = hist[i] * (sizeof(BAR) - 1.0) / hist[maxi] + 0.5;
printf("%.*s\n", len, BAR);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment