robot_name: rand() -> c++11 random
This commit is contained in:
parent
287152896a
commit
77c36f8e10
1 changed files with 14 additions and 5 deletions
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <set>
|
#include <set>
|
||||||
|
#include <random>
|
||||||
|
|
||||||
|
|
||||||
namespace robot_name {
|
namespace robot_name {
|
||||||
|
|
@ -11,14 +12,18 @@ using namespace std;
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
|
typedef uniform_int_distribution<char> distribution_t;
|
||||||
|
|
||||||
const size_t alpha_part_size = 2;
|
const size_t alpha_part_size = 2;
|
||||||
const size_t digit_part_size = 3;
|
const size_t digit_part_size = 3;
|
||||||
|
|
||||||
|
|
||||||
string random_string(size_t size, char from_char, char to_char)
|
string random_string(size_t size, distribution_t &distribution)
|
||||||
{
|
{
|
||||||
auto random_char = [from_char, to_char]() -> char {
|
static default_random_engine engine;
|
||||||
return from_char + rand() % (to_char - from_char + 1);
|
|
||||||
|
auto random_char = [&distribution]() -> char {
|
||||||
|
return distribution(engine);
|
||||||
};
|
};
|
||||||
|
|
||||||
string result(size, 0);
|
string result(size, 0);
|
||||||
|
|
@ -40,12 +45,16 @@ void robot::reset()
|
||||||
static set<name_t> used_names;
|
static set<name_t> used_names;
|
||||||
static const size_t name_capacity = pow('Z' - 'A' + 1, alpha_part_size)
|
static const size_t name_capacity = pow('Z' - 'A' + 1, alpha_part_size)
|
||||||
* pow('9' - '0' + 1, digit_part_size);
|
* pow('9' - '0' + 1, digit_part_size);
|
||||||
|
|
||||||
|
static distribution_t alpha_distribution('A', 'Z');
|
||||||
|
static distribution_t digit_distribution('0', '9');
|
||||||
|
|
||||||
string new_name;
|
string new_name;
|
||||||
|
|
||||||
do {
|
do {
|
||||||
|
|
||||||
new_name = random_string(alpha_part_size, 'A', 'Z')
|
new_name = random_string(alpha_part_size, alpha_distribution)
|
||||||
+ random_string(digit_part_size, '0', '9');
|
+ random_string(digit_part_size, digit_distribution);
|
||||||
|
|
||||||
} while (used_names.size() < name_capacity && used_names.count(new_name));
|
} while (used_names.size() < name_capacity && used_names.count(new_name));
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue