Class: Dogfood::Randomness
- Inherits:
-
Object
- Object
- Dogfood::Randomness
- Defined in:
- lib/dogfood/randomness.rb
Instance Attribute Summary collapse
-
#seed ⇒ Object
readonly
Returns the value of attribute seed.
Instance Method Summary collapse
- #branch(weights) ⇒ Object
-
#initialize(seed: nil) ⇒ Randomness
constructor
A new instance of Randomness.
- #pick(collection) ⇒ Object
- #rand(range = nil) ⇒ Object
- #sample(collection, count) ⇒ Object
Constructor Details
#initialize(seed: nil) ⇒ Randomness
Returns a new instance of Randomness.
7 8 9 10 |
# File 'lib/dogfood/randomness.rb', line 7 def initialize(seed: nil) @seed = seed || Random.new_seed @random = Random.new(@seed) end |
Instance Attribute Details
#seed ⇒ Object (readonly)
Returns the value of attribute seed.
5 6 7 |
# File 'lib/dogfood/randomness.rb', line 5 def seed @seed end |
Instance Method Details
#branch(weights) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/dogfood/randomness.rb', line 12 def branch(weights) total = weights.values.sum.to_f threshold = @random.rand * total cumulative = 0.0 weights.each do |key, weight| cumulative += weight return key if threshold < cumulative end weights.keys.last end |
#pick(collection) ⇒ Object
25 26 27 |
# File 'lib/dogfood/randomness.rb', line 25 def pick(collection) collection.sample(random: @random) end |
#rand(range = nil) ⇒ Object
33 34 35 |
# File 'lib/dogfood/randomness.rb', line 33 def rand(range = nil) range ? @random.rand(range) : @random.rand end |
#sample(collection, count) ⇒ Object
29 30 31 |
# File 'lib/dogfood/randomness.rb', line 29 def sample(collection, count) collection.sample(count, random: @random) end |