fluffy/entropy.c

29 lines
366 B
C
Raw Permalink Normal View History

2018-01-08 16:39:44 -07:00
#include <stdio.h>
#include <math.h>
int
main(int argc, char *argv[])
{
size_t len = 0;
size_t hist[256] = {0};
int c;
2018-05-15 14:43:47 -06:00
int i;
2018-01-08 16:39:44 -07:00
while ((c = getchar()) != EOF) {
hist[c] += 1;
len += 1;
}
float H = 0;
2018-05-15 14:43:47 -06:00
for (i = 0; i < 256; i += 1) {
2018-01-08 16:39:44 -07:00
if (hist[i]) {
float Hi = (float)hist[i]/len;
H -= Hi * log2(Hi);
}
}
printf("%f\n", H);
2018-10-15 12:54:51 -06:00
return 0;
2018-01-08 16:39:44 -07:00
}