mvper7
mvper7

Reputation: 17

C++ get random number in several ranges

How I can get random number in several ranges? For example, I ask numbers in range 5-10 and 18-53.

My main goal is generate random password by using ASCII table (https://uk.wikipedia.org/wiki/%D0%A4%D0%B0%D0%B9%D0%BB:ASCII-Table.svg). So I generate a random number 33-126. But before generating password I should ask about what password user wants (numbers, lowercase letters, uppercase letters, symbols). When user ask me generate password for him with numbers and lowercase letters, I need get number 48-57 and 97-122.

I guess I can use smth like do while to generate number in loop till that moment when it is correct.

But mb there is a better option?

Upvotes: 0

Views: 127

Answers (1)

Caleth
Caleth

Reputation: 62616

You can generate numbers in a contiguous range, and map those to the desired values.

template <std::uniform_random_bit_generator URBG>
char uniform_lower_alphanumeric(URBG&& gen) {
    std::uniform_int_distribution dist(0, 35);
    auto value = dist(gen);
    if (value < 10) return static_cast<char>('0' + value);
    return static_cast<char>('a' + value - 10);
}

Or more simply

template <std::uniform_random_bit_generator URBG>
char uniform_lower_alphanumeric(URBG&& gen) {
    auto lower_alphanumerics = "0123456789abcdefghijklmnopqrstuvwxyz";
    std::uniform_int_distribution dist(0, std::size(lower_alphanumerics) - 1);
    return lower_alphanumerics[dist(gen)];
}

Upvotes: 2

Related Questions