RosettaCodeData/Task/Entropy/JavaScript/entropy.js

16 lines
364 B
JavaScript
Raw Normal View History

2019-09-12 10:33:56 -07:00
const entropy = (s) => {
const split = s.split('');
const counter = {};
split.forEach(ch => {
if (!counter[ch]) counter[ch] = 1;
else counter[ch]++;
});
2015-02-20 00:35:01 -05:00
2019-09-12 10:33:56 -07:00
const lengthf = s.length * 1.0;
const counts = Object.values(counter);
return -1 * counts
.map(count => count / lengthf * Math.log2(count / lengthf))
.reduce((a, b) => a + b);
};