Skip to content

Instantly share code, notes, and snippets.

@Au-lit
Last active April 16, 2021 23:15
Show Gist options
  • Save Au-lit/eacd4ef9cdf5fa3b11cdc7496798fa30 to your computer and use it in GitHub Desktop.
Save Au-lit/eacd4ef9cdf5fa3b11cdc7496798fa30 to your computer and use it in GitHub Desktop.
A "simple" C++ function for random values...
// © Copyright 2021 Ollivier Roberge
#ifndef RANDOM_VALUE_IMPL
#define RANDOM_VALUE_IMPL
#include <limits>
#include <random>
#include <type_traits>
template<typename ResultType>
#if __has_cpp_attribute(nodiscard) >= 201603L
[[nodiscard]]
#endif
ResultType uniform_random_value(
ResultType a = 0,
ResultType b = std::numeric_limits<ResultType>::max()
) noexcept {
thread_local std::random_device rd;
thread_local std::default_random_engine random_engine(rd());
if constexpr (std::is_floating_point<ResultType>::value)
return std::uniform_real_distribution<ResultType>(a, b).operator()(random_engine);
else if constexpr (std::is_same<ResultType, bool>::value)
return std::bernoulli_distribution().operator()(random_engine);
else return std::uniform_int_distribution<ResultType>(a, b).operator()(random_engine);
}
#endif // !defined(RANDOM_VALUE_IMPL)

A "simple" C++ function for random values : uniform_random_value()

To use uniform_random_value() include/paste the header random_value.hpp from this gist in your project; you can after simply write :

int randomInt = uniform_random_value(1, 100);
float randomFloat = uniform_random_value(1.0f, 100.0f);
double randomDouble = uniform_random_value(1.0, 100.0);

For the instance where you want a random boolean you can write :

bool randomBool = uniform_random_value<bool>();

When you have diferrent input types (assuming they are implicitly convertible) choose the right one with the syntax :

auto randomValue = uniform_random_value<theTypeYouWant>(aValue, anOtherValueWithAnOtherType);
// For example :
float randomFloat = uniform_random_value<float>(1u, 100.0f); // (a mix of unsigned and float)

© Copyright 2021 Ollivier Roberge

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment