Skip to content

Commit

Permalink
Added random sampler using reservoir sampling.
Browse files Browse the repository at this point in the history
  • Loading branch information
oderwat committed Mar 8, 2015
1 parent 9426ecf commit ba4dc9a
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/random/common.nim
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,19 @@ iterator randomSample*(rng: var RNG; arr: RAContainer; n: Natural): auto =
else:
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
else:
let r = self.randomInt(idx)
if r < n:
result[r] = e
inc idx

0 comments on commit ba4dc9a

Please sign in to comment.