Class: Reservoir
Direct Known Subclasses
Instance Attribute Summary collapse
-
#sample_size ⇒ Object
Returns the value of attribute sample_size.
-
#total ⇒ Object
Returns the value of attribute total.
Instance Method Summary collapse
- #<<(obj) ⇒ Object
- #add(list) ⇒ Object
- #clear ⇒ Object
- #full? ⇒ Boolean
-
#initialize(sample_size) ⇒ Reservoir
constructor
A new instance of Reservoir.
Methods included from Enumerable
#average, #count_by, #geometric_mean, #histogram, #length_of_longest, #length_of_shortest, #longest, #median, #median_by, #percentile, #percentile_by, #rfind, #shortest, #to_percent, #to_ratio, #triangle, #with_previous
Constructor Details
#initialize(sample_size) ⇒ Reservoir
Returns a new instance of Reservoir.
14 15 16 17 18 |
# File 'lib/muflax/reservoir.rb', line 14 def initialize sample_size @sample_size = sample_size @total = 0 @reservoir = [] end |
Instance Attribute Details
#sample_size ⇒ Object
Returns the value of attribute sample_size.
12 13 14 |
# File 'lib/muflax/reservoir.rb', line 12 def sample_size @sample_size end |
#total ⇒ Object
Returns the value of attribute total.
12 13 14 |
# File 'lib/muflax/reservoir.rb', line 12 def total @total end |
Instance Method Details
#<<(obj) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/muflax/reservoir.rb', line 20 def <<(obj) if @total < @sample_size # fill empty slot in the reservoir @reservoir << obj else # randomly replace elements in the reservoir with a decreasing probability r = rand(0..@total) @reservoir[r] = obj if r < @sample_size end @total += 1 end |
#add(list) ⇒ Object
33 |
# File 'lib/muflax/reservoir.rb', line 33 def add list ; list.each{|x| self << x} ; end |
#clear ⇒ Object
34 |
# File 'lib/muflax/reservoir.rb', line 34 def clear ; @reservoir.clear; @total = 0 ; end |
#full? ⇒ Boolean
35 |
# File 'lib/muflax/reservoir.rb', line 35 def full? ; @reservoir.size >= @sample_size ; end |