Entropy/Narcissist: Difference between revisions

→‎{{header|Ruby}}: DATA & __END__ => __FILE__
(→‎{{header|Ruby}}: DATA & __END__ => __FILE__)
Line 287:
=={{header|Ruby}}==
<lang ruby>def entropy(s)
counts = s.charseach_char.each_with_objectwith_object(Hash.new(0.0)) {|c,h| h[c] += 1}
counts.values.reduce(0) do |entropy, count|
freq = count.fdiv( / s.size)
entropy - freq * Math.log2(freq)
end
end
s = File.read(__FILE__)
 
p entropy(s)</lang>
DATA.rewind
strings = DATA.readlines.map(&:chomp).join
puts entropy(strings)
 
__END__</lang>
 
{{out}}
<pre>
4.885234973253878
4.956480298256947
</pre>
 
Anonymous user