diff options
author | WhiteDuke <Wh1teDuke@users.noreply.github.com> | 2019-02-25 16:45:44 +0100 |
---|---|---|
committer | Andreas Rumpf <rumpf_a@web.de> | 2019-02-25 16:45:44 +0100 |
commit | 1397ad7c5459d48c10cc19d487dc856bcb78e81a (patch) | |
tree | 6bb86348db6efc9f4ed228135c182b3912de88e4 /lib/pure/random.nim | |
parent | bf4e688ca37ebfcedd64d2c8cb1854b287f56037 (diff) | |
download | Nim-1397ad7c5459d48c10cc19d487dc856bcb78e81a.tar.gz |
[random] add support for sets (#10532)
* Support for sets * Rename 'rand' to 'sample' * Update random.nim
Diffstat (limited to 'lib/pure/random.nim')
-rw-r--r-- | lib/pure/random.nim | 12 |
1 files changed, 12 insertions, 0 deletions
diff --git a/lib/pure/random.nim b/lib/pure/random.nim index 86db7da49..4115d147b 100644 --- a/lib/pure/random.nim +++ b/lib/pure/random.nim @@ -390,6 +390,18 @@ proc rand*[T](a: openArray[T]): T {.deprecated.} = ## Use `sample[T](openArray[T])<#sample,openArray[T]>`_ instead. result = a[rand(a.low..a.high)] +proc sample*[T](r: var Rand; s: set[T]): T = + ## returns a random element from a set + assert card(s) != 0 + var i = rand(r, card(s) - 1) + for e in s: + if i == 0: return e + dec(i) + +proc sample*[T](s: set[T]): T = + ## returns a random element from a set + sample(state, s) + proc sample*[T](r: var Rand; a: openArray[T]): T = ## Returns a random element from ``a`` using the given state. ## |