module Ronin::Support::Text::Entropy

Implements the [Shanno Entropy] algorithm.

[Shannon Entropy]: en.wikipedia.org/wiki/Entropy_(information_theory)

@since 1.0.0

@api public

Public Class Methods

calculate(string, base: 2) click to toggle source

Calculates the entropy for the given string.

@param [String] string

The given string to calculate the entropy for.

@param [Integer] base

The base to calculate the entropy for.

@return [Float]

The entropy for the string.
# File lib/ronin/support/text/entropy.rb, line 44
def self.calculate(string, base: 2)
  char_counts = Hash.new(0)

  string.each_char do |char|
    char_counts[char] += 1
  end

  length  = string.length.to_f
  entropy = 0.0

  char_counts.each_value do |count|
    freq     = count / length
    entropy -= freq * Math.log(freq,base)
  end

  return entropy
end