Skip to content

Instantly share code, notes, and snippets.

@alwynallan
Created August 31, 2021 07:59
Show Gist options
  • Save alwynallan/7543d86d111c5fa885020022ab842fe2 to your computer and use it in GitHub Desktop.
Save alwynallan/7543d86d111c5fa885020022ab842fe2 to your computer and use it in GitHub Desktop.
Solution per tstanisl at https://stackoverflow.com/a/68959383/5660198 and pmg's 2nd comment
#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<100000; j++) {
values[0] = 0.; // https://stackoverflow.com/a/68959383/5660198
for(i=1; i<n; i++) values[i] = grand_f_0_1();
qsort(values+1, n-1, sizeof(double), compare); // only sort 9
shift = grand_f_0_1() * (1. - values[n-1]); // keeps values in sorted order
for(i=0; i<n; i++) {
values[i] += shift;
if(values[i] >= 1.) {
values[i] -= 1.;
fprintf(stderr, "encountered value >= 1\n");
}
}
// cannot resort here!
for(i=0; i<n; i++) {
diffs[i] = values[(i+1)%n] - values[i];
if(diffs[i] < 0.) {
diffs[i] += 1.;
if(i < (n-1)) fprintf(stderr, "corrected a diff in the first 9\n");
}
}
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