#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.
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8aXRlcmF0b3I+CiNpbmNsdWRlIDx2ZWN0b3I+CiNpbmNsdWRlIDxhbGdvcml0aG0+CgovL0Z1bmN0aW9uIGZvciBhcnJheQpzdGQ6OnZlY3RvcjxpbnQ+IG1vZGUoY29uc3Qgc3RkOjp2ZWN0b3I8aW50PiYgdmFsdWVzKQp7CiAgICBzdGQ6OnZlY3RvcjxpbnQ+IG1vZGVzOwogICAgaWYgKHZhbHVlcy5lb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