Skip to content

Instantly share code, notes, and snippets.

@justinmeiners
Last active January 16, 2021 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinmeiners/675a029d5d819601f3fae8c3f544b88d to your computer and use it in GitHub Desktop.
Save justinmeiners/675a029d5d819601f3fae8c3f544b88d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
template<typename I>
std::pair< typename std::iterator_traits<I>::value_type, size_t> mode(I start, I end) {
typedef typename std::iterator_traits<I>::value_type V;
if (start == end) {
return std::make_pair(V(), 0);
}
std::vector< V > sorted;
std::copy(start, end, std::back_inserter(sorted));
std::sort(sorted.begin(), sorted.end());
size_t best_len = 1;
auto it = sorted.begin();
auto best_group = it;
auto group_start = it;
++it;
while (it != sorted.end()) {
if (*it != *group_start) {
size_t len = it - group_start;
if (len > best_len) {
best_len = len;
best_group = group_start;
}
group_start = it;
}
++it;
}
return std::make_pair(*best_group, best_len);
}
int main()
{
int test[] = { 1, 2, 3, 4, 4, 3, 4, 5, 6, 6 };
auto item = mode(test, test + sizeof(test) / sizeof(int));
std::cout << item.first << ", " << item.second <<std::endl;
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment