英文:
C++ get random number in several ranges
问题
如何在多个范围内获取随机数?例如,我要求在范围5-10和18-53内获取数字。
我的主要目标是使用ASCII表(https://uk.wikipedia.org/wiki/%D0%A4%D0%B0%D0%B9%D0%BB:ASCII-Table.svg)生成随机密码。因此,我生成一个随机数33-126。但在生成密码之前,我应该询问用户想要什么密码(数字、小写字母、大写字母、符号)。当用户要求我生成包含数字和小写字母的密码时,我需要获取数字48-57和小写字母97-122。
我猜我可以使用类似“do while”的方法,在循环中生成数字,直到达到正确的条件。
但也许还有更好的选择?
英文:
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?
答案1
得分: 2
以下是翻译好的部分:
你可以在一个连续的范围内生成数字,并将它们映射到所需的值。
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);
}
或者更简单地:
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)];
}
英文:
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)];
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论