Skip to content

Instantly share code, notes, and snippets.

@tmattio
Last active September 20, 2016 21:21
Show Gist options
  • Save tmattio/e82438382e729c155e9ea71c1f84af91 to your computer and use it in GitHub Desktop.
Save tmattio/e82438382e729c155e9ea71c1f84af91 to your computer and use it in GitHub Desktop.
A set of few functions for generating random values
// Created by Thibaut Mattio
#pragma once
#include <ctime>
#include <random>
namespace random {
inline auto random_float(float min = 0., float max = 1.) {
srand(static_cast<unsigned>(time(nullptr)));
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_real_distribution<float> uni(min, max);
return uni(rng);
}
inline auto random_int(int min, int max) {
srand(static_cast<unsigned>(time(nullptr)));
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<int> uni(min, max);
return uni(rng);
}
inline auto random_string(size_t size) {
auto *alpha_num = "0123456789abcdefghijklmnopqrstuvwxyx";
auto gen_rand_char = [alpha_num]() {
return alpha_num[random_int(0, strlen(alpha_num) - 1)];
};
std::string random_str{};
for (auto i = 0; i < size; ++i) {
random_str += gen_rand_char();
}
return random_str;
}
inline auto random_bytes(size_t size) {
srand(static_cast<unsigned>(time(nullptr)));
std::random_device rd;
auto *data = new unsigned char[size];
for (auto i = 0; i < size; ++i) {
*(data + i) = rd();
}
return data;
}
} // namespace random
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment