Sha256: c906c1225070c220fd40131281fc9663980aa6aa792e0989afcea1105194e796

Contents?: true

Size: 700 Bytes

Versions: 10

Compression:

Stored size: 700 Bytes

Contents

module Enumerable

  # Generates a hash mapping each unique element in the array
  # to the relative frequency, i.e. the probablity, of
  # it appearence.
  #
  # CREDIT: Brian Schröder

  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

  # old def
  #
  #   def probability
  #     arr = self.to_a
  #     probHash = Hash.new
  #     size = arr.size.to_f
  #     arr.uniq.each do |i|
  #       ct = arr.inject(0) do |mem,obj|
  #         obj.eql?(i) ? (mem+1) : mem
  #       end
  #       probHash[i] = ct.to_f/size
  #     end
  #     probHash
  #   end

end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-2.8.4 lib/core/facets/enumerable/probability.rb
facets-2.8.3 lib/core/facets/enumerable/probability.rb
facets-2.8.2 lib/core/facets/enumerable/probability.rb
facets-2.8.1 lib/core/facets/enumerable/probability.rb
facets-2.8.0 lib/core/facets/enumerable/probability.rb
facets-2.7.0 lib/core/facets/enumerable/probability.rb
facets-2.6.0 lib/core/facets/enumerable/probability.rb
facets-2.5.1 lib/core/facets/enumerable/probability.rb
facets-2.5.0 lib/core/facets/enumerable/probability.rb
facets-2.5.2 lib/core/facets/enumerable/probability.rb