75 lines
1.4 KiB
C++
75 lines
1.4 KiB
C++
#include "robot_name.h"
|
|
|
|
#include <algorithm>
|
|
#include <stdexcept>
|
|
#include <set>
|
|
#include <random>
|
|
|
|
|
|
namespace robot_name {
|
|
|
|
using namespace std;
|
|
|
|
|
|
namespace {
|
|
|
|
typedef uniform_int_distribution<char> distribution_t;
|
|
|
|
const size_t alpha_part_size = 2;
|
|
const size_t digit_part_size = 3;
|
|
|
|
|
|
string random_string(size_t size, distribution_t &distribution)
|
|
{
|
|
static default_random_engine engine;
|
|
|
|
auto random_char = [&distribution]() -> char {
|
|
return distribution(engine);
|
|
};
|
|
|
|
string result(size, 0);
|
|
generate_n(result.begin(), size, random_char);
|
|
|
|
return result;
|
|
};
|
|
|
|
}
|
|
|
|
|
|
robot::robot()
|
|
{
|
|
reset();
|
|
}
|
|
|
|
void robot::reset()
|
|
{
|
|
static set<name_t> used_names;
|
|
static const size_t name_capacity = pow('Z' - 'A' + 1, alpha_part_size)
|
|
* pow('9' - '0' + 1, digit_part_size);
|
|
|
|
static distribution_t alpha_distribution('A', 'Z');
|
|
static distribution_t digit_distribution('0', '9');
|
|
|
|
if (used_names.size() >= name_capacity)
|
|
throw length_error("no more names available");
|
|
|
|
string new_name;
|
|
|
|
do {
|
|
|
|
new_name = random_string(alpha_part_size, alpha_distribution)
|
|
+ random_string(digit_part_size, digit_distribution);
|
|
|
|
} while (used_names.count(new_name));
|
|
|
|
used_names.erase(name_);
|
|
name_ = new_name;
|
|
used_names.insert(name_);
|
|
}
|
|
|
|
const name_t &robot::name() const
|
|
{
|
|
return name_;
|
|
}
|
|
|
|
}
|