Skip to content
Browse files

Added random sampler using reservoir sampling.

  • Loading branch information...
oderwat committed Mar 8, 2015
1 parent 9426ecf commit ba4dc9a836ab74aec5ece12852953d29d0d6ced2
Showing with 16 additions and 0 deletions.
  1. +16 −0 src/random/common.nim
@@ -166,3 +166,19 @@ iterator randomSample*(rng: var RNG; arr: RAContainer; n: Natural): auto =
for i in iset.missingItems(0, n-1):
yield arr[i]

proc randomSample*[T](self: var RNG; iter: iterator(): T; n: Natural): seq[T] =
## Random sampling using reservoir sampling algorithm.
## It will pick random `n` items from the iterator very efficiently.
result = newSeq[T](n)
var idx = 0
for e in iter():
if idx < n:
result[idx] = e
let r = self.randomInt(idx)
if r < n:
result[r] = e
inc idx

0 comments on commit ba4dc9a

Please sign in to comment.
You can’t perform that action at this time.