Entropy: Difference between revisions

→‎{{header|Ruby}}: Use tally method
(→‎{{header|Ruby}}: Use tally method)
Line 2,914:
 
=={{header|Ruby}}==
 
{{works with|Ruby|1.9}}
<syntaxhighlight lang="ruby">def entropy(s)
counts = Hashs.new(0chars.0)tally
leng = s.length.to_f
s.each_char { |c| counts[c] += 1 }
leng = s.length
counts.values.reduce(0) do |entropy, count|
freq = count / leng
Line 2,931 ⟶ 2,930:
1.8464393446710154
</pre>
One-liner, same performance (or better):
<syntaxhighlight lang="ruby">def entropy2(s)
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</syntaxhighlight>
 
=={{header|Run BASIC}}==
1,149

edits