shadowtalker
shadowtalker

Reputation: 13893

Randomly sampling an item always returns the same value

I am attempting to write a script that samples one of my colleagues' names randomly:

#!/usr/bin/env gosh -b

(define-module utils
  (use data.random :only (samples$ integers-between$))
  (use gauche.generator :only (generator->list))
  (export generator->first
          sample1)

  (define (generator->first gen)
    (car (generator->list gen 1)))

  (define (sample1 items)
    (generator->first (samples$ items))))


(import (utils :only (sample1)))

(define team-members
  (list "billy"
        "nilly"
        "silly"
        "willy"))

(define (main args)
  (print (sample1 team-members))
  0)

However it always emits the same value:

for i in {1..25}; do
  gosh ./random-team-member
done

Why is this happening?

Do I need to somehow initialize the random number generator? Am I misusing generator->list?

Upvotes: 0

Views: 295

Answers (1)

amalloy
amalloy

Reputation: 92067

Observe the documentation for data.random.

The random seed is initialized by a fixed value when the module is loaded. You can get and set the random seed [with random-data-seed].

I don't see any obvious way to initialize the random seed from some other source of randomness, such as the system clock. So if you want unpredictable randomness, you'll need to find entropy yourself - perhaps read from /dev/urandom?

Upvotes: 2

Related Questions