Hello everyone,
I have to create a program that gives out the mode, the number that appears the most ofen, of a vector with positive integers.
Actually, I tried something, but I didn't really get foward.
So, here is my code so far:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <math.h>
#include <fstream>
usingnamespace std;
int mode(vector<int> s) //as i could'nt find a solution, i wanted at least to
//check whether i can write a
//function that gives out the amount of the mode
{
int z = 0;
vector <int> mode; // store the amount of one integer in a new vector
sort(s.begin(), s.end());
int x = 0;
while (x<s.size())
{
if (x == 0) { ++x; }; //this should avoid out of range error
if (s[x] - s[x - 1] == 0){ // are neighbouring ints equal?
++z;
++x;
}
elseif (s[x] - s[x - 1] != 0 && z > 0) { //store z;
mode.push_back(z);
z = 0;
++x;
}
else {
z = 0;
++x;
}
}
sort(mode.begin(), mode.end());
int i;
for (i = 0; i<mode.size(); ++i);
int m = mode[i]; //give out biggest value of mode vector
return m;
} //i still get a vector subscript out of range error
int main() {
vector <int> numbers;
int max = 10;
int y;
cout << "Enter " << max << " integers!\n";
for (int i = 0; i < max; ++i) {
cin >> y;
numbers.push_back(y);
}
sort(numbers.begin(), numbers.end()); //thought, this might be helpful
for(int x = 0; x < max; ++x)
cout << numbers[x] << endl;
mode(numbers);
cin.get();
return 0;
}
So yeah, I actually don't have much ideas now, so perhaps a hint would be enough in the first case.
And the assignment is actually to write a program that prints out the number of the mode, so my code isn't fullfilling the task at all, yet I thought, the mode-function could perhaps help me.
Thank you for your reply. :-) I think this will help. It's a task from Stroustrup's book, Chapter 4.
I see, you use "maps", these aren't introduced in the chapter yet, so I will read about them and check whether I can understand your solution.
int getMode(std::vector<int>& vec)
{
std::sort(vec.begin() , vec.end() ); // sort vector
int mode = vec[0]; // set mode to first element of vector
int occurrence = 1; // its occurred once so far
int maxOccurrence = 1; // and maxOccurrence therefore is also 1
for(int i = 1; i < vec.size(); i++)
{
// if we see a new number, set occurence to 1
if(vec[i] > vec[i-1]){ occurrence = 1; }
else occurrence++; // if same number, simply increment occurrence
// if occurrence is bigger than or equal to maxOccurrence, we found a new mode
if(occurrence >= maxOccurrence)
{
maxOccurrence = occurrence; // update maxOccurrence
mode = vec[i]; // update mode
}
}
return mode;
}
This takes advantage of a sorted vector (as you sort in the OP as well). Also keep in mind that if the vector contains multiple modes (i.e. different numbers that appear equally as frequently), this function will return the number greatest in value.