lundi 28 septembre 2015

Calculating chance of adding char to string

So my objective is to create a random password generator of length n (n >= 5 && n <= 15) that adds in only two numbers at random locations.

(e.g. 7S4js 86dJxD h6Zqs9K)

I have this working... or so I want to believe. What I want to know is will my code ALWAYS work at determining whether or not a number should be inserted.

'newPassword': Returns a string of length 'len', using 'nums' numbers.

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': Returns a random character. The character will be a number if 'isNum' is true.

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;
}

So specifically, will the 'chance' variable in 'newPassword' work all the time?




Aucun commentaire:

Enregistrer un commentaire