Class: Reservoir

Inherits:
Object show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/muflax/reservoir.rb

Direct Known Subclasses

HardReservoir

Instance Attribute Summary collapse

Instance Method Summary collapse

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_sizeObject

Returns the value of attribute sample_size.



12
13
14
# File 'lib/muflax/reservoir.rb', line 12

def sample_size
  @sample_size
end

#totalObject

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

#clearObject



34
# File 'lib/muflax/reservoir.rb', line 34

def clear     ; @reservoir.clear; @total = 0     ; end

#full?Boolean

Returns:

  • (Boolean)


35
# File 'lib/muflax/reservoir.rb', line 35

def full?     ; @reservoir.size >= @sample_size  ; end