add sample proc with exclude array (#68)

This commit is contained in:
Dmitriy Ryajov 2022-04-05 08:24:39 -06:00 committed by GitHub
parent 3222f436cc
commit 8ef8cfcd74
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 18 additions and 0 deletions

View File

@ -7,10 +7,15 @@
## This file may not be copied, modified, or distributed except according to ## This file may not be copied, modified, or distributed except according to
## those terms. ## those terms.
import pkg/upraises
push: {.upraises: [].}
import pkg/libp2p/crypto/crypto import pkg/libp2p/crypto/crypto
import pkg/bearssl import pkg/bearssl
type type
RngSampleError = object of CatchableError
Rng* = ref BrHmacDrbgContext Rng* = ref BrHmacDrbgContext
var rng {.threadvar.}: Rng var rng {.threadvar.}: Rng
@ -36,6 +41,19 @@ proc rand*(rng: Rng, max: Natural): int =
proc sample*[T](rng: Rng, a: openArray[T]): T = proc sample*[T](rng: Rng, a: openArray[T]): T =
result = a[rng.rand(a.high)] result = a[rng.rand(a.high)]
proc sample*[T](
rng: Rng, sample, exclude: openArray[T]): T
{.raises: [Defect, RngSampleError].} =
if sample == exclude:
raise newException(RngSampleError, "Sample and exclude arrays are the same!")
while true:
result = rng.sample(sample)
if exclude.find(result) != -1:
continue
break
proc shuffle*[T](rng: Rng, a: var openArray[T]) = proc shuffle*[T](rng: Rng, a: var openArray[T]) =
for i in countdown(a.high, 1): for i in countdown(a.high, 1):
let j = rng.rand(i) let j = rng.rand(i)