【问题标题】:Calculating percent chance计算百分比机会
【发布时间】:2015-09-29 00:49:07
【问题描述】:

所以我的目标是创建一个长度为 n (n >= 5 && n

(例如 7S4js 86dJxD h6Zqs9K)

我有这个工作......或者我想相信。我想知道的是我的代码是否总是能确定是否应该插入一个数字。

'newPassword':返回长度为 'len' 的字符串,使用 'nums' 数字。

std::string newPassword(int len, int nums)
{
    std::string password = "";

    // Required numbers
    int req = nums;

    for (int i = 0; i < len; i++)
    {
        bool needNum = req > 0;

        bool chance = rand() % len > req;

        bool useNum = needNum && chance;

        if (useNum)
            req--;

        char c = nextChar(useNum);

        password += c;
    }

    return password;
}

'nextChar':返回一个随机字符。如果 'isNum' 为真,该字符将是一个数字。

char nextChar(bool isNum)
{
    char c;

    if (!isNum)
    {
        // 50% chance to decide upper or lower case
        if (rand() % 100 < 50)
        {
            c = 'a' + rand() % 26;
        }
        else
        {
            c = 'A' + rand() % 26;
        }
    }
    else
    {
        // Random number 0-9
        c = '0' + rand() % 10;
    }

    return c;
}

具体来说,'newPassword' 中的 'chance' 变量会一直有效吗?

【问题讨论】:

    标签: c++ random logic percentage


    【解决方案1】:

    rand() 是一种过时且糟糕的生成随机数的方法。 c++11 &lt;random&gt; 标头为处理各种随机内容提供了更高质量的工具。

    您选择字母或数字的方式并不总是有效。我会以不同的方式处理它:生成所需数量的字母和数字,然后打乱字符串。这可能不是最有效的方法,但考虑到您对密码长度的要求,我会更加重视代码的清晰度。

    #include <string>
    #include <random>
    #include <algorithm>
    
    std::string generatePassword(int length, int nDigits)
    {
        std::string password;
        password.resize(length);
    
        std::mt19937 generator{std::random_device{}()};
    
        // Generate capital/lowercase letters
        std::uniform_int_distribution<char> letterGen(0, 2 * 26 - 1);
        auto digitsBeginIter = std::generate_n(password.begin(), length - nDigits, 
                      [&letterGen, &generator]() { 
                          auto l = letterGen(generator); 
                          return l < 26 ? 'a' + l : 'A' + (l - 26); 
                      });
    
        // Generate the digits
        std::uniform_int_distribution<char> digitGen('0', '9');
        std::generate_n(digitsBeginIter, nDigits, 
                        [&digitGen, &generator]() { return digitGen(generator); });
    
        // Shuffle the string
        std::shuffle(password.begin(), password.end(), generator);
    
        return password;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-05
      • 1970-01-01
      • 2011-06-01
      • 2021-01-10
      • 1970-01-01
      • 2015-10-11
      • 2015-09-04
      • 2013-03-22
      相关资源
      最近更新 更多