我一直在做彩票检查计划。目标是创建一个查找重复项的函数,并允许用户在userTicket的情况下选择另一个数字,并在winsNums的情况下生成另一个随机数。因此,此功能必须可以在两者之间重复使用,或者与任何数组相关。我还不熟悉排序和扫描阵列。我创建了一个嵌套的for循环来遍历每个索引并比较[i]和[j]之间的两个。由于某种原因,我的功能仅适用于第一个数字。任何想法都非常感谢。
void getLottoPicks(int userArray[])
{
cout << "Please enter your 7 lotto number picks between 1 and 40.\n";
for (int i = 0; i < NUMS; i++)
{
cout << "selection #" << i + 1 << ":";
cin >> userArray[i];
cin.ignore();
if (noDuplicates(userArray) == true)
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> userArray[i];
}
}
}
void genWinNums(int winArray[])
{
srand((int)time(NULL));
for (int i = 0; i < NUMS; i++)
{
winArray[i] = rand() % 40 + 1;
if (noDuplicates(winArray) == true)
{
winArray[i] = rand() % 40 + 1;
}
}
}
bool noDuplicates(int dupArray[])
{
int temp = 0;
for (int i = 0; i < NUMS; i++)
{
//temp += dupArray[i];
for (int j = 0; j < i; j++)
{
if (dupArray[i] == dupArray[j])
{
return true;
}
else
{
return false;
}
}
}
}
答案 0 :(得分:0)
您可以使用std::set
,它更快,代码更少
void getLottoPicks(std::set<int> userArray)
{
cout << "Please enter your 7 lotto number picks between 1 and 40.\n";
for (int i = 0; i < NUMS; i++)
{
cout << "selection #" << i + 1 << ":";
int num;
cin >> num;
cin.ignore();
// while the num is already in the set
while (userArray.find(num) != userArray.end())
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> num;
}
}
}
答案 1 :(得分:0)
在这两种情况下,对noDuplicates()
的调用都嵌套在构造传递给noDuplicates()
的数组的循环中。那不行。首先,您需要构建数组,一旦完成构建,然后将其传递给noDuplicates()
。