Find the mode (most common element) of an array in C++ -
i had on interview question. i'd see how stackoverflow it.
what bjarne stroustrop think of way? it's little wordy, don't know how make better, unfortunately. know guys gonna laugh @ stupidity.
template <class t> t mode(t* arr, size_t n) // if there's tie, return arbitrary element tied 1st // if array size 0, throw error { if (n == 0) { throw("mode of array of size 0 undefined, bro."); } else if (n == 1) { return arr[0]; } else { std::pair<t, int> highest(arr[0], 1); std::map<t, int> s; s.insert(highest); (t* thisptr(arr + 1), lastptr(arr+n); thisptr != lastptr; ++thisptr) { if (s.count(*thisptr) == 0) { s.insert(std::pair<t, int> (*thisptr, 1); } else { ++s[*thisptr]; if (s[*thisptr] > highest.second) { highest = std::pair<t, int> (*thisptr, s[*thisptr]); } } } } }
you this, provided t implements std::hash
:
std::unordered_multiset<t> elems; std::for_each(arr, arr + size, [&elems](t const & elem) { elems.insert(elem); } //now have elems.count() each entry auto max_count = /*guaranteed minimum value*/ t mode{}; (auto const & set_elem : elems) { if (max(elems.count(set_elem), max_count) == max_count)) { mode = set_elem; } }
Comments
Post a Comment