Skip to content

Commit

Permalink
Add note about reservoir sampling
Browse files Browse the repository at this point in the history
  • Loading branch information
HertzDevil committed Jan 12, 2021
1 parent c3ab3b8 commit bf8fd37
Showing 1 changed file with 5 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/enumerable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1254,6 +1254,11 @@ module Enumerable(T)
def sample(n : Int, random = Random::DEFAULT)
raise ArgumentError.new("Can't sample negative number of elements") if n < 0

# Unweighted reservoir sampling:
# https://en.wikipedia.org/wiki/Reservoir_sampling#Simple_algorithm
# "Algorithm L" does not provide any performance improvements on Enumerable,
# because it is not possible to discard multiple elements at once

ary = Array(T).new(n)
return ary if n == 0

Expand Down

0 comments on commit bf8fd37

Please sign in to comment.