diff options
| author | Tom Smeding <tom@tomsmeding.com> | 2024-09-08 22:44:19 +0200 | 
|---|---|---|
| committer | Tom Smeding <tom@tomsmeding.com> | 2024-09-08 22:44:55 +0200 | 
| commit | f017c53ec62b03e34c4ba4eb80eb3ec82bbff4ff (patch) | |
| tree | 7498e306125b5f36837c5391585e6493d98b1420 | |
| parent | fd5c5611c4df1e99a7d158ac91f04e54889125cd (diff) | |
hus: Correcte verdeling (hopelijk)
Code is niet getest, want dat is irritant en heb ik geen zin in
| -rw-r--r-- | src/hus.c | 21 | 
1 files changed, 21 insertions, 0 deletions
| @@ -3,6 +3,7 @@  #include <getopt.h>  #include <pwd.h>  #include <stdlib.h> +#include <stdint.h>  #include <string.h>  #include <sys/random.h>  #include <sys/types.h> @@ -17,6 +18,19 @@ static char *shufrange = NULL;  static char **lines = NULL;  static size_t nlines = 0; +static size_t random_size_t_r(struct random_data *buf) { +  size_t res = 0; +  unsigned nbytes = 0; +  while (nbytes < sizeof(size_t)) { +    int32_t value; +    int ret = random_r(buf, &value); +    if (ret == -1) { fprintf(stderr, "hus: Kon willekeurigheid niet verlengen\n"); exit(1); } +    res |= (size_t)value << (8 * nbytes); +    nbytes += 4; +  } +  return res; +} +  static void shuf_lines() {    size_t *js = calloc(nlines, sizeof(size_t));    errno = 0; @@ -24,6 +38,13 @@ static void shuf_lines() {    for (ssize_t i = nlines - 1; i > 0; i--) {      size_t j = js[i] % (nlines-1); +    if (j - 1 + (nlines-1) < j) { +      struct random_data buf; +      int ret = srandom_r(js[i], &buf); +      if (ret == -1) { fprintf(stderr, "hus: Kon willekeurigheidsverlenging niet instellen\n"); exit(1); } +      do j = random_size_t_r(&buf) % (nlines-1); +      while (j - 1 + (nlines-1) < j); +    }      char *x = lines[i];      lines[i] = lines[j]; | 
