Skip to content

Instantly share code, notes, and snippets.

@walac
Last active December 28, 2015 05:29
Show Gist options
  • Save walac/7449901 to your computer and use it in GitHub Desktop.
Save walac/7449901 to your computer and use it in GitHub Desktop.
Some random stuff.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <unordered_map>
using namespace std;
namespace {
template <typename IteratorT, typename OutIteratorT> void
enum_patterns(
IteratorT it,
IteratorT end,
OutIteratorT &out,
const basic_string<typename iterator_traits<IteratorT>::value_type> &pattern)
{
typedef typename iterator_traits<IteratorT>::value_type char_t;
if (it == end) {
*out++ = pattern;
return;
}
if (*it != char_t('?')) {
enum_patterns(it+1, end, out, pattern + *it);
} else {
enum_patterns(it+1, end, out, pattern + char_t('1'));
enum_patterns(it+1, end, out, pattern + char_t('0'));
}
}
}
template<typename IteratorT, typename OutIteratorT> void
enum_patterns(IteratorT first, IteratorT end, OutIteratorT out)
{
typedef basic_string<typename iterator_traits<IteratorT>::value_type> string_type;
enum_patterns(first, end, out, string_type(""));
}
template<typename Iterator> Iterator
most_frequent(Iterator first, Iterator end)
{
typedef typename iterator_traits<Iterator>::value_type value_type;
typedef unordered_map<value_type, size_t> map_type;
typedef typename map_type::value_type map_value_type;
map_type freq_table;
for_each(first, end, [&freq_table] (const value_type &x) { ++freq_table[x]; });
return find(
first,
end,
max_element(
freq_table.begin(),
freq_table.end(),
[] (const map_value_type &a, const map_value_type &b)
{ return a.second < b.second; })->first);
}
int
main(void)
{
vector<string> v;
char s[] = "1?0?";
enum_patterns(begin(s), end(s), back_inserter(v));
copy(begin(v), end(v), ostream_iterator<string>(cout, "\n"));
string ss("1?0?");
v.clear();
enum_patterns(begin(ss), end(ss), back_inserter(v));
copy(begin(v), end(v), ostream_iterator<string>(cout, "\n"));
vector<int> v2 = {1,2,3,3,3,4,5,6};
cout << *most_frequent(begin(v2), end(v2)) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment