I am using the following code to compute the mode
#include <iosfwd>
#include <vector>
#include <iostream>
int prices[]={1,1,2,2,2,3,3,3};
int main()
{
double currval=prices[0];
int ctr=1;
int maxctr=1;
double modval=prices[0];
for (int i=1;i<8;i++) {
if(prices[i]==currval) {
++ctr;
}else {
if(ctr>maxctr) {
maxctr=ctr;
modval=currval;
}
currval=prices[i];
ctr=1;
}
}
std::cout<<"mode is: "<<modval<<std::endl;
return 0;
}
but unfortunately, this returns the first mode.
mode is: 2
I want to continue to pass over the array and capture all the modes in another array, so then I can select the max or min or average of the array of modes. So, in my example, I would have an array with content {2,3}.
any suggestions on how I do that.
thanks!
EDITED:
#include <iosfwd>
#include <vector>
#include <iostream>
int prices[]={1,1,2,2,2,3,3,3};
std::vector<int> result;
int main()
{
double currval=prices[0];
int ctr=1;
int maxctr=1;
double modval=prices[0];
for (int i=1;i<8;i++) {
if(prices[i]==currval) {
++ctr;
}else {
if(ctr>maxctr) {
maxctr=ctr;
result.clear();
result.push_back(currval);
} else {
if (ctr==maxctr) {
result.push_back(currval);
}
}
currval=prices[i];
ctr=1;
}
}
if(ctr>maxctr) {
maxctr=ctr;
result.clear();
result.push_back(currval);
} else {
if (ctr==maxctr) {
result.push_back(currval);
}
}
return 0;
}
Your code’s part after else was wrong, as it will get executed after both
ifandelsewhich is not what wanted.Assuming array is in ascending order.
But if you want to store min or max or avg you can do this without using vector.
For min while transverse don’t change mode if it has same count as old one
For max you will assign new value for same count
For avg, just add all numbers but keep track of how many number added. then at end of loop just take
avg = sum / no. of elementSo in all three cases, vector isn’t required.