Re: C++ programming challenge
Here's a submission in C++. Nothing that interesting, but to
illustrate a
point: the speed of this program is dominated by the printing of the
floating point value representing percent. i.e., this line:
cout << ("abcdefghijklmnopqrstuvwxyz")[i] << ' ' << p <<"%\n";
if you remove "<< p" it will only take 0.158s on my computer. With
that in, it takes
0.514s. Perhaps it's just g++'s implementation of cout's float to text
processing.
In any event, I think we're at the mercy of the compiler's libs.
For what it's worth I also coded up a version that read longs instead
of chars, and
accumulated 16 bits at a time in the "count" array (fixing the
calculation at the
end). This didn't make much of a difference, though, in light of the
cout penalty
noted above.
//-----------------------------------------------------------------------------------
#include <cstdio>
#include <iostream>
using ::std::cout;
using ::std::endl;
#define BUFFSIZE 4096
int main(int argc, char* argv[]) {
if( argc <= 1 ) return (printf("Please provide a file name\n"), 1);
CStopWatch s;
s.startTimer();
if (FILE* f = fopen(argv[1], "r")) {
unsigned char buff[BUFFSIZE];
unsigned long count[256] = {0};
unsigned long total_alpha[26] = {0};
size_t bytesread;
while ((bytesread = fread(buff, 1, BUFFSIZE, f)) > 0) {
for (size_t i = 0; i < bytesread; ++i) {
++count[buff[i]];
}
}
unsigned long total = 0;
for (int i = 0; i < 26; ++i) {
unsigned long x;
x = count[("abcdefghijklmnopqrstuvwxyz")[i]]
+ count[("ABCDEFGHIJKLMNOPQRSTUVWXYZ")[i]];
total_alpha[i] = x;
total += x;
}
float p2 = 100.0f / total;
for (int i = 0; i < 26; ++i) {
float p = p2 * total_alpha[i];
cout << ("abcdefghijklmnopqrstuvwxyz")[i] << ' ' << p <<"%\n";
}
cout << endl;
fclose(f);
}
s.stopTimer();
cout << "Time elapsed: " << s.getElapsedTime() << endl;
return 0;
}