Commit 8e77bd6e authored by GILLES Sebastien's avatar GILLES Sebastien

#1482 Introduce a utility function to generate a random string.

parent 2ee3cccf
......@@ -17,6 +17,7 @@
#include <vector>
#include <sstream>
#include <algorithm>
#include <random>
#include "Utilities/String/String.hpp"
......@@ -286,6 +287,25 @@ namespace MoReFEM
}
std::string GenerateRandomString(std::size_t length,
const std::string& charset)
{
assert(charset.size() >= 2ul);
std::random_device random_device;
std::default_random_engine random_engine(random_device());
std::uniform_int_distribution<std::size_t> distribution(0ul, charset.size() - 1ul);
auto randchar = [&charset, &distribution, &random_engine]()
{
assert(distribution.max() == charset.size() - 1ul);
return charset[distribution(random_engine)];
};
std::string ret(length, 0);
std::generate_n(ret.begin(), length, randchar);
return ret;
}
} // namespace String
......
......@@ -180,6 +180,23 @@ namespace MoReFEM
std::string ConvertCharArray(const std::vector<char>& array);
/*!
* \brief Generates a random string of size \a length (useful for tests...).
*
* \param[in] length Size of the expected string (as returned by size() method).
* \param[in] charset All characters in this string may be used in the generated string. If a given char
* is present more than once, it is more likely to be picked.
*
* This code is inspired from
* https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c
*
* \return The random string.
*/
std::string GenerateRandomString(std::size_t length,
const std::string& charset =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
} // namespace String
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment