Re: C++ programming challenge
This is the best I have:
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <iomanip>
#include <math.h>
#include <fstream>
#include "CStopWatch.hpp"
const int MAX_TEXT_LENGTH = 65536;
int freq[256];
double pctFreq[256];
int count = 0;
int main(int argc, char** argv) {
memset(freq, 0, sizeof (int) * 256);
memset(pctFreq, 0, sizeof (double) * 256);
unsigned char text[MAX_TEXT_LENGTH];
int diff = 'a' - 'A';
std::ios_base::sync_with_stdio(false);
CStopWatch s;
s.startTimer();
//std::ifstream file(argv[1], std::ios::in);
std::ifstream file(argv[1], std::ios::in | std::ios::binary);
do {
file.read((char *) text, MAX_TEXT_LENGTH);
for (std::streamsize i(0), num(file.gcount()); i < num; ++i) {
++freq[text[i]];
}
} while (!file.eof());
file.close();
for (char i = 'A'; i <= 'Z'; i++) {
freq[i] += freq[i + diff];
count += freq[i];
}
for (char i = 'A'; i <= 'Z'; i++) {
pctFreq[i] = round((double(freq[i]) / count)*10000) / 100;
std::cout << i << ": " << std::setw(5) << std::setfill('0') <<
std::fixed << std::setprecision(2) << pctFreq[i] << "%\n";
}
s.stopTimer();
std::cout << "Time [microseconds]: " << s.getElapsedTime()*1.0E6
<< '\n';
return (EXIT_SUCCESS);
}