Suppose I have a text file which contains 10,000 random values between 0 and 1, and I want to count the number of values within a specific interval. An example may explain it more clearly.
Suppose my Datefile.txt contains data like:
0.0102244
0.028072
0.0144578
0.064578
0.08148
0.012749
0.12749.....and 10,000 more values
And I want to count the number of values within the interval 0.05 (i.e. it searches for the values within the range 0.0 to 0.05, then 0.05 to 0.1 and so on). For the example above, the output will be:
In range 0 to 0.05, total values 4
In range 0.05 to 0.1, total values 2
In range 0.1 to 0.15, total values 1...etc.
Here is my code:
int main(){
double area;
double a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0;
ifstream theFile ("Datafile.txt");
while(theFile >>area){
if (area<=0.05){
a++;
}
else if (area<=0.1){
b++;
}
else if (area<=0.15){
c++;
}
else if (area<=0.2){
d++;
}
else if (area<=0.25){
e++;
}
else if (area<=0.3){
f++;
}
else if (area<=0.35){
g++;
}
else if (area<=0.4){
h++;
}
else if (area<=0.45){
i++;
}
else if (area<=0.5){
k++;
}
else if (area<=0.55){
l++;
}
else if (area<=0.6){
m++;
}
else if (area<=0.65){
n++;
}
else if (area<=0.7){
o++;
}
else if (area<=0.75){
p++;
}
else if (area<=0.8){
q++;
}
else if (area<=0.85){
r++;
}
else if (area<=0.9){
s++;
}
else if (area<=0.95){
t++;
}
else if (area<=1.0){
u++;
}
}
Though my code is working fine, it might not be the most efficient way. So I put my code here for review. Can anyone suggest a better way of doing this?
Updated (based on the answer of ChrisWue)
#include <iostream> #include <cmath> #include <vector> #include <fstream> using namespace std; int main() { const double bucket_size = 0.05; double area=0; int number_of_buckets = (int)ceil(1 / bucket_size); std::vector<int> histogram(number_of_buckets); ifstream theFile("Datafile.txt"); while (theFile >> area) { int bucket = (int)floor(area / bucket_size); histogram[bucket] += 1; } for (auto loop = histogram.begin(); loop != histogram.end();++loop) { cout<<bucket_size<<"\t"<<number_of_buckets<<endl; } return 0; }
For the data-
0.0102244
0.028072
0.0144578
0.064578
0.08148
0.012749
0.12749.....
it gives the output like this-
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
0.05 20
What am I doing wrong?
ranges
. If you need more explanation, I can put this into an answer. \$\endgroup\$std::map
(which may be preferred), and I'll check it in case I've made any mistakes. \$\endgroup\$