We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 9426ecf commit ba4dc9aCopy full SHA for ba4dc9a
src/random/common.nim
@@ -166,3 +166,19 @@ iterator randomSample*(rng: var RNG; arr: RAContainer; n: Natural): auto =
166
else:
167
for i in iset.missingItems(0, n-1):
168
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