I am trying to write a simulator for playing the Powerball lottery, where the program would ask for 5
numbers (aka the white balls) and be inputted into a 6
element array and another number (the red Powerball) into the 6
th element.
I need to figure out how to test for duplicates in the first 5
elements but the 6
th doesn't need to be unique.
I have a loop that I thought would work but it doesn't even execute and is rather messy.
Is there a more efficient way to test for duplicates, maybe involving a bool flag?
const int PBALLAMOUNT = 6;
const int PBMAX = 69;
const int PBMIN = 1;
const int REDMAX = 26;
cout << "Enter the numbers you want to use for the white powerballs" << endl;
for (int k = 0; k < PBALLAMOUNT - 1; k++)
{
cin >> pBallNums[k];
while (pBallNums[k] < PBMIN || pBallNums[k]>PBMAX)
{
cout << "Invalid input! Please enter different numbers between 1 and 69" << endl;
cin >> pBallNums[k];
}
}
bool dup = false;
for (int i = 0; i < PBALLAMOUNT - 1; i++)
{
for (int j = i + 1; j < PBALLAMOUNT - 1; j++)
{
while (!dup)
{
if (pBallNums[i] == pBallNums[j])
{
cout << "Please enter a unique number from the others in your PowerBall number selection" << endl;
cin >> pBallNums[i];
}
}
}
}
cout << "And what would you like for your redball" << endl;
cin >> pBallNums[5];
while (pBallNums[5] < PBMIN || pBallNums[5] > REDMAX)
{
cout << " The red powerball needs to be between 1 and 26: ";
cin >> pBallNums[5];
}
I basically just need it to alert the user if they have already entered a number into the array and offer another std::cin >> pBallNums
statement but the actual result is just nothing happens after you enter the numbers.
Sort, then check adjacent items for equality.
First, try not to mix real requirements with implementation details.
What you really want is: 5 distinct numbers taken from user input. And from your code I read that the check should happen after each single input. I suppose reading the last number is fine, so lets leave that aside.
Next, get acustomed to the containers in the standard library. They are not many in numbers but what you can do with them is uncountable. To have distinct elements in a container you want either
std::unsorted_set
orstd::set
. Then basically all you need is to useinsert
:prints:
In that case simply use
std::set
and use it'sstd::set::emplace
method to store the user input into the set.From cppreference.com,
Simply take this information for your case and loop again for the next user input.
Here is a sample code (See Live):
Sample input:
Output: