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