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 if
and else
which is not what wanted.
#include <iosfwd>
#include <vector>
#include <iostream>
int prices[]={1,1,2,2,2,3,3,3};
using namespace std;
int main()
{
int ctr=1;
int maxctr=1;
vector<int> allModes;
int max, min;
for (int i=0; i<8; i++) {
if(prices[i+1]==prices[i]) {
++ctr;
}
else {
if(ctr == maxctr) {
allModes.push_back(prices[i]); //if it is same as previous mode add it to vector
//max = prices[i];
}
if(ctr > maxctr) {
allModes.clear(); //if it is greater than previous mode then previous number is not a mode now
//so clear old vector
allModes.push_back(prices[i]);
maxctr = ctr;
//max = prices[i];
//min = prices[i];
}
ctr=1;
}
}
std::cout<<"Mode: ";
for ( vector<int>::iterator it=allModes.begin() ; it < allModes.end(); ++it ) {
std::cout<< " " << *it;
}
return 0;
}
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 element
So in all three cases, vector isn't required.