Advertisement
Guest User

Untitled

a guest
Aug 29th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. std::vector<int> Mode(std::vector<int> &myvector)
  2. {
  3. int vectorsize = myvector.size();
  4. int max = 0;
  5. std::vector<int> maxs;
  6. int counter = 1;
  7. std::sort(_vector.begin(), myvector.end());
  8.  
  9. for (int i = 0; i < vectorsize - 1; i++)
  10. {
  11. int currentnum = myvector[i];
  12.  
  13. if (currentnum == myvector[i + 1])
  14. {
  15. counter++;
  16. if (counter > vectorsize - i) break; //early exit when the mode found so far appears more than the number of elements still to be evaluated
  17.  
  18. if (counter > max)
  19. {
  20. max = counter;
  21. if (maxs.size() > 0) maxs.clear();
  22. maxs.push_back(currentnum);
  23. }
  24. else if (counter == max)
  25. {
  26. bool alreadyin = false;
  27. for (int j = 0; j < maxs.size(); j++)
  28. {
  29. if (maxs[j] == currentnum)
  30. {
  31. alreadyin = true;
  32. break;
  33. }
  34. }
  35. if (alreadyin == false)
  36. maxs.push_back(currentnum);
  37. }
  38.  
  39. }
  40. else counter = 1; //reset the counter
  41. }
  42.  
  43. return (maxs.size() > 0) ? maxs : myvector; //if all elements appear only once, return the whole initial vector; otherwise return the the modes that were found
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement