Here is my own entry to the
programming challenge "Letter Frequency" that is written in another post.
#include "cctype"
#include "fstream"
#include "iostream"
#include "CStopWatch.hpp"
int main( int argc, char** argv)
{
unsigned long int freq[256];
for( int i(0); i < 256; ++i )
{
freq[i] = 0UL;
}
CStopWatch s;
s.startTimer();
std::ifstream f(argv[1],std::ios::binary);
for( unsigned char buf[1024]; f.read((char*)buf,1024); )
{
for( std::streamsize i(0), num( f.gcount() );
i < num; ++i )
{
++freq[ buf[i] ];
}
}
f.close();
unsigned long int N(0UL);
for( int i('a'); i <= 'z'; ++i )
{
N += freq[i];
}
for( int i('A'); i <= 'Z'; ++i )
{
N += freq[i];
freq[ std::tolower((char)i) ] += freq[i];
freq[i] = 0UL;
}
const double scale(100.0/N);
for( int i('a'); i <= 'z'; ++i )
{
std::cout<<(char)i<<' '
<<freq[i]*scale<<"%\n";
}
s.stopTimer();
std::cout<<"Time [microseconds]: "
<<s.getElapsedTime()*1.0E6<<'\n';
return 0;
}Outputs on my machine:
a 6.91958%
b 1.16229%
c 4.20517%
d 3.31721%
e 11.6445%
f 2.5592%
g 1.89503%
h 3.82255%
i 7.81837%
j 0.101068%
k 0.638897%
l 3.39662%
m 2.36789%
n 6.86543%
o 9.38132%
p 2.80104%
q 0.126336%
r 7.86529%
s 6.06411%
t 8.82183%
u 2.9743%
v 1.18033%
w 1.49798%
x 0.202137%
y 2.33179%
z 0.0397055%
Time [microseconds]: 846880
0 kommentarer:
Post a Comment