In: Computer Science
//find the code below
#include<bits/stdc++.h>
using namespace std;
vector<int> readCsv()
{
string fname;
cout<<"enter name of file :";
cin>>fname;
fstream fin;
fin.open(fname);
string temp,line;
vector<int> nums;
while(fin>>temp)
{
getline(fin,line);
stringstream ss(line);
string word;
while(getline(ss,word,',')){
remove(word.begin(),word.end(),' ');
int n =
stoi(word);
nums.push_back(n);
}
}
fin.close();
return nums;
}
float total=0,avg=0,variance=0,sd=0;
void calcStats(vector<int> num)
{
total=0;avg=0;variance=0;sd=0;
int n = num.size();
for(int i=0;i<n;i++)
{
total+=num[i];
}
avg = total/n;
double sqDiff = 0;
for(int i=0;i<n;i++)
{
sqDiff +=
(num[i]-avg)*(num[i]-avg);
}
variance = sqDiff/n;
sd = sqrt(variance);
}
void writeStats(string uname)
{
string fname;
cout<<"enter output file name\n";
cin>>fname;
fstream fout;
fout.open(fname,ios::out);
fout<<uname<<"\n";
fout<<"---------------------\n";
fout<<"Total :
"<<fixed<<setprecision(2)<<total<<"\n";
fout<<"Average
:"<<fixed<<setprecision(2)<<avg<<"\n";
fout<<"Variance
:"<<fixed<<setprecision(2)<<variance<<"\n";
fout<<"StDev
:"<<fixed<<setprecision(2)<<sd<<"\n";
fout.close();
}
class Counter{
public:
vector<int> cnt;
Counter()
{
for(int i=0;i<13;i++)
{
cnt.push_back(0);
}
}
void increment(int idx)
{
cnt[idx]++;
}
void showCount()
{
for(int i=2;i<=12;i++)
{
cout<<i<<"| "<<cnt[i]<<"\n";
}
}
void normalize()
{
for(int i=2;i<=12;i++)
{
cnt[i]/=1000;
}
}
};
Counter counter;
void letsCount(vector<int> nums)
{
int n=nums.size();
for(int i=0;i<n;i++)
{
counter.increment(nums[i]);
}
}
void displayBar()
{
for(int i=2;i<=12;i++)
{
cout<<i<<"|";
for(int
j=0;j<counter.cnt[i];j++)
cout<<"X";
cout<<endl;
}
}
int main()
{
cout<<"----------MENU--------\n";
cout<<"1. Load From a File\n";
cout<<"2. Calculate the Statistics\n";
cout<<"3. Write to a File\n";
cout<<"4. Perform the count\n";
cout<<"5. Display the Bargraph\n";
cout<<"6. Quit\n\n";
cout<<"enter your name\n";
string uname;
cin>>uname;
int choice = 0;
vector<int> nums;
while(1)
{
cin>>choice;
switch(choice)
{
case 1:
nums.clear(); nums=readCsv(); break;
case 2:
calcStats(nums); break;
case 3:
writeStats(uname); break;
case 4:
letsCount(nums); counter.showCount(); break;
case 5:
counter.normalize(); displayBar(); break;
case 6:
cout<<"Quitting"; return 0;
default :
cout<<"Invalid choice\n";;
}
}
return 0;
}