C++在多个范围内获取随机数

huangapple go评论64阅读模式
英文:

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 &lt;std::uniform_random_bit_generator URBG&gt;
char uniform_lower_alphanumeric(URBG&amp;&amp; gen) {
    std::uniform_int_distribution dist(0, 35);
    auto value = dist(gen);
    if (value &lt; 10) return static_cast&lt;char&gt;(&#39;0&#39; + value);
    return static_cast&lt;char&gt;(&#39;a&#39; + value - 10);
}

Or more simply

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

huangapple
  • 本文由 发表于 2023年2月6日 18:54:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75360379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定