1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
// http://ideone.com/SrvApG
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
//Function for array
std::vector<int> mode(const std::vector<int>& values)
{
std::vector<int> modes;
if (values.empty()) // if values is empty, there is no mode.
return std::vector<int>();
if (values.size() == 1) // if values has size 1, the only element is the mode.
return std::vector<int>(1, values.front());
// Begin with a max_run length of 1 with the initial element as the mode.
modes.push_back(values.front());
std::size_t max_run_length = 1;
// let index i be 0.
std::size_t i = 0;
// while i is less than the size of the array less 1,
while (i < values.size() - 1)
{
// let run length be 1
std::size_t current_run_length = 1;
// while i is a valid index and the current and previous values match, increase the run length.
while (++i < values.size() && values[i] == values[i - 1])
++current_run_length;
// if the run length is equal to the longest run length found so far, add the value for this run
// to the list of mode candidates.
if (current_run_length == max_run_length)
modes.push_back(values[i - 1]);
// else, if run length is greater than the longest run length found so far, remove the current
// mode candidates, set the maximum run length to the current run length, and add the current
// run value to the mode candidates.
else if (current_run_length > max_run_length)
{
modes.clear();
modes.push_back(values[i - 1]);
max_run_length = current_run_length;
}
}
// return the modes.
return modes;
}
int main()
{
int array [] = { 23, 5, -10, 0, 0, 321, 1, 1, 99, 30 };
int size = 10;
std::sort(array, array + size);
for (int i = 0; i < size; i++)
std::cout << array[i] << std::endl;
std::vector<int> modeVector; //vector creating
modeVector = mode(std::vector<int>(std::begin(array), std::end(array))); //calling function
std::cout << "The modes calculated are:\n";
for (std::size_t i = 0; i < modeVector.size(); i++)
std::cout << '\t' << modeVector[i] << '\n'; //printing vector mode details.
}
|