Razii said:
I think you are a little confused. This is not the sorting bible
problem. This one counts up the frequency of each word, and it makes
no difference if the data is already sorted. The sort is done to print
output (.e words) in nice format. Here, I wilt post it to a blogpage
that explains it..
Why is C++ slower than Java?
http://razi2.blogspot.com/2008/04/why-is-c-slower-than-java.html
Yawn. What a lame attempt at trolling.
Anyway, a few changes and down to 750 ms from 6500 ms:
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstring>
static const int num_morons = ('z' - 'a' + 1) * 2;
template <typename T> class MoronicArray {
T arr[num_morons];
public:
T &operator[](unsigned char c) {
int n;
if(c >= 'a' && c <= 'z')
n = c - 'a';
else if(c >= 'A' && c <= 'Z')
n = c- 'A' + num_morons/2;
else
n = 0;
return arr[n];
}
MoronicArray() { memset(this, '\0', sizeof(*this)); }
};
class Moron {
MoronicArray<int> counts;
MoronicArray<Moron *> morons;
public:
Moron *operator[](unsigned char c) {
Moron *&m = morons[c];
if(m != NULL)
return m;
return m = new Moron();
};
void inc(unsigned char c) {
++counts[c];
};
void moronificator(const std::string &s) {
for(unsigned char c = 'a'; c <= 'z'; ++c) {
if(counts[c] > 0)
std::cout << s << c << " " << counts[c] <<
std::endl;
if(morons[c])
morons[c]->moronificator(s + std::string(1,
c));
}
for(unsigned char c = 'A'; c <= 'Z'; ++c) {
if(counts[c] > 0)
std::cout << s << c << " " << counts[c] <<
std::endl;
if(morons[c])
morons[c]->moronificator(s + std::string(1,
c));
}
}
};
int main(int argc, char **argv)
{
int w_total = 0, l_total = 0, c_total = 0;
Moron m;
printf(" lines words bytes file\n" );
clock_t start=clock();
for(int i = 1; i <argc; ++i) {
std::ifstream input_file(argv
);
std:stringstream buffer;
buffer << input_file.rdbuf();
const std::string &s = buffer.str();
int l = s.size();
int w_cnt = 0, l_cnt = 0, c_cnt = 0;
Moron *act = &m;
unsigned char last = '\0';
for(int j = 0; j < l; ++j) {
unsigned char c = s[j];
if(c == '\n') {
++l_cnt;
}
if(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
if(last)
act = (*act)[last];
last = c;
} else if(last) {
act->inc(last);
act = &m;
last = '\0';
} else {
last = '\0';
}
++c_cnt;
}
printf("%d\t%d\t%d\t %s\n", l_cnt, w_cnt, c_cnt, argv);
l_total += l_cnt;
w_total += w_cnt;
c_total += c_cnt;
}
clock_t end=clock();
if(argc > 2) {
printf("--------------------------------------\n%d\t%d\t%d\t
total",
l_total, w_total, c_total);
}
printf("--------------------------------------\n");
m.moronificator(std::string());
std::cout <<"Time: " << double(end-start)/CLOCKS_PER_SEC * 1000 << "
ms\n";
}
Lrf, guvf boivbhfyl jnf n wbxr :C.