Sha256: e3fd536cf1ea19ea4962215c77dcfc6f97b082c154bb0f98545b3f421890d052

Contents?: true

Size: 1.07 KB

Versions: 26

Compression:

Stored size: 1.07 KB

Contents

#--
# Credit goes to Brian Schröder for current code
# and Derek for original.
#++
module Enumerable

  # Generates a hash mapping each unique symbol in the array
  # to the relative frequency, i.e. the probablity, of
  # it appearence.
  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



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCEnumerable < Test::Unit::TestCase

    def test_probability
      assert_equal( {'a'=>0.5,'b'=>0.5}, %w{a b}.probability )
      assert_equal( {'tom'=>0.5,'boy'=>0.5}, %w{tom boy}.probability )
    end

  end

=end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
facets-1.0.0 lib/facet/enumerable/probability.rb
facets-0.9.0 lib/nano/enumerable/probability.rb
facets-1.0.3 packages/core/lib/facet/enumerable/probability.rb
facets-1.2.1 lib/facets/core/enumerable/probability.rb
facets-1.2.0 lib/facets/core/enumerable/probability.rb
facets-1.3.0 lib/facets/core/enumerable/probability.rb
facets-1.1.0 lib/facet/enumerable/probability.rb
facets-1.3.2 lib/facets/core/enumerable/probability.rb
facets-1.3.1 lib/facets/core/enumerable/probability.rb
facets-1.3.3 lib/facets/core/enumerable/probability.rb
facets-1.4.2 lib/facets/core/enumerable/probability.rb
facets-1.4.0 lib/facets/core/enumerable/probability.rb
facets-1.4.1 lib/facets/core/enumerable/probability.rb
facets-1.4.3 lib/facets/core/enumerable/probability.rb
facets-1.4.4 lib/facets/core/enumerable/probability.rb
facets-1.4.5 lib/facets/core/enumerable/probability.rb
facets-1.7.38 lib/facets/core/enumerable/probability.rb
facets-1.7.0 lib/facets/core/enumerable/probability.rb
facets-1.7.30 lib/facets/core/enumerable/probability.rb
facets-1.7.46 lib/facets/core/enumerable/probability.rb