【发布时间】: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