Class: Suimin::Sleeper
- Inherits:
-
Object
- Object
- Suimin::Sleeper
- Defined in:
- lib/suimin/sleeper.rb
Defined Under Namespace
Classes: InvalidRuleException
Instance Attribute Summary collapse
-
#distribution ⇒ Object
readonly
Returns the value of attribute distribution.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
Instance Method Summary collapse
- #expected_sleep_duration_value ⇒ Object
-
#initialize(_config) ⇒ Sleeper
constructor
_config:i The name of the sleeper instance.
-
#rule ⇒ Object
converts the distribution to cdf.
- #sleep ⇒ Object
- #sleep_duration ⇒ Object
Constructor Details
#initialize(_config) ⇒ Sleeper
_config:i The name of the sleeper instance. _config: An array of arrays whose element is [probablility, sleep_duration_in_second]
For example [0.5, 1] means the probablity of sleeping for 1 second is 0.5
If sum of the probability isn't 1.0, the probablities are normalized automatically.
For example, [[1.0, 1], [1.0, 3]] => [[0.5, 1], [0.5, 3]]
12 13 14 15 |
# File 'lib/suimin/sleeper.rb', line 12 def initialize(_config) @distribution = normalize_distribution(_config[:distribution]).sort{|a,b| a[0] <=> b[0]} @name = _config[:name] end |
Instance Attribute Details
#distribution ⇒ Object (readonly)
Returns the value of attribute distribution.
5 6 7 |
# File 'lib/suimin/sleeper.rb', line 5 def distribution @distribution end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
5 6 7 |
# File 'lib/suimin/sleeper.rb', line 5 def name @name end |
Instance Method Details
#expected_sleep_duration_value ⇒ Object
34 35 36 |
# File 'lib/suimin/sleeper.rb', line 34 def expected_sleep_duration_value distribution.inject(0.0) {|res, elm| res += elm[0] * elm[1] } end |
#rule ⇒ Object
converts the distribution to cdf
18 19 20 21 |
# File 'lib/suimin/sleeper.rb', line 18 def rule @rule || @distribution.inject([]){|result, elm| result << [(result.empty? ? 0.0 : result.last[0]) + elm[0], elm[1]]}\ .tap{|array| array.last[0] = 1.0 } # make sure the last element's cdf is 1.0 end |
#sleep ⇒ Object
23 24 25 |
# File 'lib/suimin/sleeper.rb', line 23 def sleep Kernel.sleep sleep_duration end |
#sleep_duration ⇒ Object
27 28 29 30 31 32 |
# File 'lib/suimin/sleeper.rb', line 27 def sleep_duration return 0 if rule.empty? _rand = SecureRandom.random_number rule.find{|elm| elm[0] >= _rand}[1] end |