<repo_name>plutonbacon/erdos<file_sep>/lib/erdos.rb
require 'erdos/version'

# Applied Mathematics
require 'erdos/infotheory'
<file_sep>/lib/erdos/infotheory.rb
module Erdos
  # Common calculations in Information Theory.
  module InfoTheory
    # Computes shannon entropy or the measure of unpredictability
    # of information content.
    #
    # @param s [String] a given input string
    # @param ignore_case [Boolean] if true, normalize to lowercase
    # @param ignore_spaces [Boolean] if true, remove all spaces
    #
    # @return [Float] The bits of entropy contained within the input string.
    def self.calculate_shannon_entropy(s, ignore_case = false,
                                       ignore_spaces = false)
      s.downcase! if ignore_case
      s.gsub!(/\s+/, '') if ignore_spaces

      s.each_char.group_by(&:to_s).values.map { |x|
        x.length / s.length.to_f
      }.reduce(0) { |e,x|
        e - x * Math.log2(x)
      }
    end # def calculate_shannon_entropy
  end # module InfoTheory
end # module Erdos
<file_sep>/spec/erdos/information_spec.rb
require 'spec_helper'

describe Erdos::InfoTheory do
  let(:s) { String.new("Lorem ipsum dolor sit amet, consectetur adipisicing " +
                           "elit, sed do eiusmod tempor incididunt ut " +
                           " labore et dolore magna aliqua.") }

  it 'computes shannon entropy correctly considering case and with spaces' do
    expect(Erdos::InfoTheory.calculate_shannon_entropy(s)).to eq(4.012206049032528)
  end

  it 'computes shannon entropy correctly not considering case and with spaces' do
    expect(Erdos::InfoTheory.calculate_shannon_entropy(s, true)).to eq(3.981004972793407)
  end

  it 'computes shannon entropy correctly not considering case and without spaces' do
    expect(Erdos::InfoTheory.calculate_shannon_entropy(s, true, true)).to eq(3.969554499580588)
  end

  it 'computes shannon entropy correctly considering case and without spaces' do
    expect(Erdos::InfoTheory.calculate_shannon_entropy(s, false, true)).to eq(4.006348221560684)
  end
end<file_sep>/README.md
# Erdos

A mathematical "goody bag" for Ruby.

### Table of Contents

#### Applied Mathematics

##### Information Theory

- [Shannon Entropy](https://github.com/plutonbacon/erdos/blob/master/lib/erdos/infotheory.rb)