RosettaCodeData/Task/Entropy/C++/entropy.cpp

27 lines
691 B
C++
Raw Permalink Normal View History

2013-10-27 22:24:23 +00:00
#include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>
double log2( double number ) {
return log( number ) / log( 2 ) ;
}
int main( int argc , char *argv[ ] ) {
std::string teststring( argv[ 1 ] ) ;
std::map<char , int> frequencies ;
for ( char c : teststring )
frequencies[ c ] ++ ;
int numlen = teststring.length( ) ;
double infocontent = 0 ;
for ( std::pair<char , int> p : frequencies ) {
double freq = static_cast<double>( p.second ) / numlen ;
2018-06-22 20:57:24 +00:00
infocontent -= freq * log2( freq ) ;
2013-10-27 22:24:23 +00:00
}
2018-06-22 20:57:24 +00:00
2013-10-27 22:24:23 +00:00
std::cout << "The information content of " << teststring
2018-06-22 20:57:24 +00:00
<< " is " << infocontent << std::endl ;
2013-10-27 22:24:23 +00:00
return 0 ;
}