Skip to content

Instantly share code, notes, and snippets.

@alwynallan
Last active August 29, 2021 12:29
Show Gist options
  • Save alwynallan/2f6d9fd125a7653dbd8d7217cafe275d to your computer and use it in GitHub Desktop.
Save alwynallan/2f6d9fd125a7653dbd8d7217cafe275d to your computer and use it in GitHub Desktop.
Bad attempt at solution per tstanisl at https://stackoverflow.com/a/68959383/5660198
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int compare (const void * a, const void * b)
{
if (*(double*)a > *(double*)b) return 1;
else if (*(double*)a < *(double*)b) return -1;
else return 0;
}
double grand_f_0_1(){
static FILE * fp = NULL;
uint64_t bits;
if(fp == NULL) fp = fopen("/dev/urandom", "r");
fread(&bits, sizeof(bits), 1, fp);
return (double)bits * 5.421010862427522170037264004349e-020; // https://stackoverflow.com/a/26867455
}
int main()
{
const int n = 10;
double values[n];
double diffs[n];
double shift;
int i, j;
for(j=0; j<10000; j++) {
values[0] = 0.; // https://stackoverflow.com/a/68959383/5660198
for(i=1; i<n; i++) values[i] = grand_f_0_1();
qsort(values, n, sizeof(double), compare);
shift = grand_f_0_1();
for(i=0; i<n; i++) {
values[i] += shift;
if(values[i] >= 1.) values[i] -= 1.;
}
qsort(values, n, sizeof(double), compare);
for(i=0; i<(n-1); i++) diffs[i] = values[i+1] - values[i];
diffs[n-1] = 1. + values[0] - values[n-1];
for(i=0; i<n; i++) printf("%.5f%s", diffs[i], i<(n-1)?"\t":"\n");
}
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment