Class: Drone::UniformSample

Inherits:
Object
  • Object
show all
Defined in:
lib/drone/utils/uniform_sample.rb

Instance Method Summary collapse

Constructor Details

#initialize(id, size) ⇒ UniformSample

Create a new instance.

Parameters:

  • id (String)

    A string which will be used by distributed storage backend to use the same value for all instances with the same id

  • size (Number)

    The size of the requested array



14
15
16
17
18
# File 'lib/drone/utils/uniform_sample.rb', line 14

def initialize(id, size)
  @id = id
  @values = Drone::request_fixed_size_array("#{id}:values", size, 0)
  @count = Drone::request_number("#{id}:count", 0)
end

Instance Method Details

#sizeObject

def clear

@values.size.times do |n|
  @values[n] = 0
end

@count.set(0)

end



28
29
30
31
# File 'lib/drone/utils/uniform_sample.rb', line 28

def size
  c = @count.get
  (c > @values.size) ? @values.size : c
end

#update(val) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/drone/utils/uniform_sample.rb', line 33

def update(val)
  @count.inc
  count = @count.get
  if count <= @values.size
    @values[count - 1] = val
  else
    r = rand(2**64 - 1) % count
    if r < @values.size
      @values[r] = val
    end
  end
end

#valuesObject



46
47
48
49
# File 'lib/drone/utils/uniform_sample.rb', line 46

def values
  # only return @count elements
  @values[0,@count.get]
end