Skip to content

Instantly share code, notes, and snippets.

@hanji
Created January 20, 2012 14:57
Show Gist options
  • Select an option

  • Save hanji/1647708 to your computer and use it in GitHub Desktop.

Select an option

Save hanji/1647708 to your computer and use it in GitHub Desktop.
I wish C++ had reflection... typeid(T).name() is just weird.
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <typeinfo>
#include <vector>
#include <boost/random.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/variate_generator.hpp>
template<typename T>
class UniformIntSampler
{
public:
UniformIntSampler()
: dist_(boost::random::uniform_int_distribution<T>()),
gen_(boost::variate_generator<boost::random::mt19937&,
boost::random::uniform_int_distribution<T> >(rng_, dist_))
{ }
T operator()() { return gen_(); }
private:
static boost::random::mt19937 rng_;
boost::random::uniform_int_distribution<T> dist_;
boost::variate_generator<boost::random::mt19937&, boost::random::uniform_int_distribution<T> > gen_;
};
template<typename T> boost::random::mt19937 UniformIntSampler<T>::rng_ =
boost::random::mt19937(static_cast<unsigned>(std::time(0)));
template<typename T>
class Sample
{
public:
Sample(const std::size_t N)
{
UniformIntSampler<T> sampler;
std::vector<T> v;
v.reserve(N);
generate_n(back_inserter(v), N, sampler);
v.swap(v_);
}
void serialize(const std::size_t ncolumns, std::ostream& os = std::cout)
{
os << "\n/* generated content */\n";
os << typeid(T).name() << " Table[" << v_.size() << "] = {\n"; // Note that the output of typeid(T).name() is weird.
std::size_t col = 0;
for_each(v_.begin(), v_.end(), [&](const T& elem){
os << "0x" << std::hex << std::setw(sizeof(T) * 2) << std::setfill('0') << elem << "," << ((++col % ncolumns) ? " " : "\n");
});
os << "};\n";
}
bool unique()
{
std::vector<T> v(v_);
std::sort(v.begin(), v.end());
v.erase(std::unique(v.begin(), v.end()), v.end());
return (v.size() == v_.size());
}
private:
std::vector<T> v_;
};
int main()
{
Sample<std::uint64_t> sample(12 * 64);
sample.serialize(6);
// the chance is rather slim. but, to pacify the paranoid...
std::cerr << (sample.unique() ? "uniqueness test is ok." : "holy shit! there're duplicates!") << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment