Merge: doc: fixed some typos and other misc. corrections
[nit.git] / examples / rosettacode / entropy.nit
1 #!/usr/bin/env nit
2 #
3 # This file is part of NIT ( http://www.nitlanguage.org ).
4 # This program is public domain
5
6 # Task: Entropy
7 # SEE: <http://rosettacode.org/wiki/Entropy>
8 module entropy
9
10 import counter
11
12 # Basic implementation with a hashmap of chars to count them
13 fun entropy(string: String): Float
14 do
15 var cpt = new HashMap[Char, Int]
16 for char in string.chars do
17 var occ = cpt.get_or_default(char, 0)
18 cpt[char] = occ + 1
19 end
20
21 var len = string.length.to_f
22 var e = 0.0
23 for char, occ in cpt do
24 var freq = occ.to_f / len
25 e = e - freq * freq.log_base(2.0)
26 end
27 return e
28 end
29 print entropy("1223334444")
30
31 # Alternative one-liner implementation using the `Counter::entropy` method of the library `counter`
32 print "1223334444".chars.to_counter.entropy