Method: Array#probability
- Defined in:
- lib/core/facets/array/probability.rb
#probability ⇒ Object
Generates a hash mapping each unique element in the array to the relative frequency, i.e. the probablity, of it appearence.
[:a, :b, :c, :c].probability #=> {:a=> 0.25, :b=>0.25, :c=>0.5}
CREDIT: Brian Schröder
10 11 12 13 14 15 16 17 18 19 |
# File 'lib/core/facets/array/probability.rb', line 10 def probability probs = Hash.new(0.0) size = 0.0 each do |e| probs[e] += 1.0 size += 1.0 end probs.keys.each{ |e| probs[e] /= size } probs end |