3 # This file is part of NIT ( http://www.nitlanguage.org ).
4 # This program is public domain
7 # SEE: <http://rosettacode.org/wiki/Entropy>
12 # Basic implementation with a hashmap of chars to count them
13 fun entropy
(string
: String): Float
15 var cpt
= new HashMap[Char, Int]
16 for char
in string
.chars
do
17 var occ
= cpt
.get_or_default
(char
, 0)
21 var len
= string
.length
.to_f
23 for char
, occ
in cpt
do
24 var freq
= occ
.to_f
/ len
25 e
= e
- freq
* freq
.log_base
(2.0)
29 print entropy
("1223334444")
31 # Alternative one-liner implementation using the `Counter::entropy` method of the library `counter`
32 print
"1223334444".chars
.to_counter
.entropy