Skip to content

Instantly share code, notes, and snippets.

@fa7ad
Last active March 10, 2016 16:34
Show Gist options
  • Save fa7ad/346506c3e1254a9cd2f0 to your computer and use it in GitHub Desktop.
Save fa7ad/346506c3e1254a9cd2f0 to your computer and use it in GitHub Desktop.
Finding mode from a list of numbers, task: https://algo.codemarshal.org/problems/556b62679c5e850300c49cb5
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
// Prototypes
std::string calculateMode(std::vector<int> array);
int main() {
int cnt,ch;
std::cin >> cnt;
std::vector< std::vector<int> > numbers(cnt);
std::ostringstream oss;
while((ch = std::cin.get()) != std::cin.eof() && ch != '\n');
for (int i = 0; i < cnt; i++) {
int number,lim;
std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
iss >> lim;
while (iss >> number) numbers[i].push_back(number);
numbers[i].resize(lim);
std::sort(numbers[i].begin(), numbers[i].end(), std::greater<int>());
oss << "Case " << i+1 << ": " << calculateMode(numbers[i]) << "\n";
}
std::cout << oss.str();
return 0;
}
std::string calculateMode(std::vector<int> array){
int counter = 1, max = 0, mode = array.at(0), size = array.size();
for (int pass = 0; pass < size - 1; pass++){
if ( array.at(pass) == array.at(pass+1) ){
counter++;
if ( counter > max ){
max = counter;
mode = array.at(pass);
}
} else {
counter = 1;
}
}
max = (max == 0) ? max + 1 : max;
std::ostringstream aMode;
aMode << mode << " " << max;
return aMode.str();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment