Skip to content

Instantly share code, notes, and snippets.

@hikilaka
Created October 7, 2016 04:21
Show Gist options
  • Save hikilaka/29bd20762a59c7239ebf96b43c9929da to your computer and use it in GitHub Desktop.
Save hikilaka/29bd20762a59c7239ebf96b43c9929da to your computer and use it in GitHub Desktop.
#ifndef SYSD_STL_UTIL
#define SYSD_STL_UTIL
#pragma once
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <random>
#include <string>
#if __has_include(<experimental/algorithm>)
# include <experimental/algorithm>
# define SYSD_has_experimental_algorithm 1
#endif
namespace sysd {
template <typename T1 = std::default_random_engine,
typename T2 = std::uniform_int_distribution<>>
struct random_selector {
using random_engine_type = T1;
using distribution_type = T2;
random_selector()
: engine(std::random_device()())
{ }
template <typename I>
auto operator()(I begin, I end) -> decltype(begin) {
auto max_range = std::distance(begin, end) - 1;
distribution_type distribution(0, max_range);
std::advance(begin, distribution(engine));
return begin;
}
private:
random_engine_type engine;
};
namespace strings {
template <typename T = std::string>
T upper_alpha = T("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
template <typename T = std::string>
T lower_alpha = T("abcdefghijklmnopqrstuvwxyz");
template <typename T = std::string>
T numeric = T("1234567890");
template <typename T = std::string>
T alpha_numeric = upper_alpha<T> + lower_alpha<T> + numeric<T>;
template <typename T = std::string>
T symbol = T("!@#$%^&*()_+-=,./<>?;':\"[]\\{}|");
template <typename T = std::string>
T alpha_numeric_symbol = alpha_numeric<T> + symbol<T>;
}
template <typename T1 = std::string,
typename T2 = std::default_random_engine>
struct string_generator {
using string_type = T1;
using random_engine_type = T2;
string_generator(string_type characters = strings::alpha_numeric_symbol<string_type>)
: characters(characters), engine(std::random_device()())
{ }
auto operator()(const std::size_t length) -> string_type {
string_type string;
std::size_t sample_size = length;
#ifdef SYSD_has_experimental_algorithm
using namespace std::experimental;
#else
using namespace std;
#endif
while (true) {
if (sample_size > characters.length()) {
sample(std::begin(characters), std::end(characters),
std::back_inserter(string), sample_size, engine);
} else {
}
}
#undef clamp
return string;
}
private:
string_type characters;
random_engine_type engine;
};
}
#endif // SYSD_STL_UTIL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment