September Morn Update
This commit is contained in:
parent
4e2d22a71d
commit
aac6731f2c
6856 changed files with 141342 additions and 21127 deletions
|
|
@ -1,31 +1,15 @@
|
|||
(function(shannon) {
|
||||
// Create a dictionary of character frequencies and iterate over it.
|
||||
function process(s, evaluator) {
|
||||
var h = Object.create(null), k;
|
||||
s.split('').forEach(function(c) {
|
||||
h[c] && h[c]++ || (h[c] = 1); });
|
||||
if (evaluator) for (k in h) evaluator(k, h[k]);
|
||||
return h;
|
||||
};
|
||||
// Measure the entropy of a string in bits per symbol.
|
||||
shannon.entropy = function(s) {
|
||||
var sum = 0,len = s.length;
|
||||
process(s, function(k, f) {
|
||||
var p = f/len;
|
||||
sum -= p * Math.log(p) / Math.log(2);
|
||||
});
|
||||
return sum;
|
||||
};
|
||||
})(window.shannon = window.shannon || {});
|
||||
const entropy = (s) => {
|
||||
const split = s.split('');
|
||||
const counter = {};
|
||||
split.forEach(ch => {
|
||||
if (!counter[ch]) counter[ch] = 1;
|
||||
else counter[ch]++;
|
||||
});
|
||||
|
||||
// Log the Shannon entropy of a string.
|
||||
function logEntropy(s) {
|
||||
console.log('Entropy of "' + s + '" in bits per symbol:', shannon.entropy(s));
|
||||
}
|
||||
|
||||
logEntropy('1223334444');
|
||||
logEntropy('0');
|
||||
logEntropy('01');
|
||||
logEntropy('0123');
|
||||
logEntropy('01234567');
|
||||
logEntropy('0123456789abcdef');
|
||||
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);
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue