Skip to content

Commit ba4dc9a

Browse files
committed
Added random sampler using reservoir sampling.
1 parent 9426ecf commit ba4dc9a

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

src/random/common.nim

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,3 +166,19 @@ iterator randomSample*(rng: var RNG; arr: RAContainer; n: Natural): auto =
166166
else:
167167
for i in iset.missingItems(0, n-1):
168168
yield arr[i]
169+
170+
proc randomSample*[T](self: var RNG; iter: iterator(): T; n: Natural): seq[T] =
171+
## Random sampling using reservoir sampling algorithm.
172+
##
173+
## It will pick random `n` items from the iterator very efficiently.
174+
result = newSeq[T](n)
175+
var idx = 0
176+
for e in iter():
177+
if idx < n:
178+
result[idx] = e
179+
else:
180+
let r = self.randomInt(idx)
181+
if r < n:
182+
result[r] = e
183+
inc idx
184+

0 commit comments

Comments
 (0)