rosetta code: entropy
authorJean Privat <jean@pryen.org>
Fri, 10 Jul 2015 15:24:15 +0000 (11:24 -0400)
committerJean Privat <jean@pryen.org>
Fri, 10 Jul 2015 15:26:41 +0000 (11:26 -0400)
Signed-off-by: Jean Privat <jean@pryen.org>

examples/rosettacode/entropy.nit [new file with mode: 0644]
tests/sav/entropy.res [new file with mode: 0644]

diff --git a/examples/rosettacode/entropy.nit b/examples/rosettacode/entropy.nit
new file mode 100644 (file)
index 0000000..f47910c
--- /dev/null
@@ -0,0 +1,32 @@
+#!/usr/bin/env nit
+#
+# This file is part of NIT ( http://www.nitlanguage.org ).
+# This program is public domain
+
+# Task: Entropy
+# SEE: <http://rosettacode.org/wiki/Entropy>
+module entropy
+
+import counter
+
+# Basic implementation with a hashmap of chars to count them
+fun entropy(string: String): Float
+do
+       var cpt = new HashMap[Char, Int]
+       for char in string.chars do
+               var occ = cpt.get_or_default(char, 0)
+               cpt[char] = occ + 1
+       end
+
+       var len = string.length.to_f
+       var e = 0.0
+       for char, occ in cpt do
+               var freq = occ.to_f / len
+               e = e - freq * freq.log_base(2.0)
+       end
+       return e
+end
+print entropy("1223334444")
+
+# Alternative one-liner implementation using the `Counter::entropy` method of the library `counter`
+print "1223334444".chars.to_counter.entropy
diff --git a/tests/sav/entropy.res b/tests/sav/entropy.res
new file mode 100644 (file)
index 0000000..29f9066
--- /dev/null
@@ -0,0 +1,2 @@
+1.846
+1.846