I'm having trouble with a part of a method I am trying to write that first generates a random number to determine the number of line items that will be part of an order, and then a loop to to randomize an inventory number that will be filled into each of the arrays elements. There will also be a method/statement to determine that their are no duplicate inventory numbers. When I am filling the array with an inventory number it just keeps using the same number as the number of line items. The intention is each time the loop iterates that the method call to the random number function will be different? I feel like this works fine when use in the main method but doesn't appearing to be working here. What am I doing wrong?
Figured it out. I didn't realize how important it was in C++ to include the seed in the main to ensure a random number. This was a habit unfortunately that I carried over from Java where having a dedicated method for random numbers would work in this capacity.
^^ but the seeding is similar, you only want to seed once unless you have a reason to repeat from the start with the same seed, which can be a nice tool for some programs. I highly advise wrapping up the c++ random tool into a wrapper class.
Thanks for the tip. Okay so the next thing I ma having trouble with is my nested loop that steps through each of arrays elements to compare to prior elements and makes sure there are no identical elements, otherwise it creates a random number again. I have tried using a while loop for this but it just keeps repeating.
void populateOrder()
{
int lineItems = getRandom(1, 10);
int i;
vector<int> pickList(lineItems);
for (i = 0; i < lineItems; i++)
{
int inventoryNumber = 0;
inventoryNumber = getRandom(1, 10);
pickList[i] = inventoryNumber;
for (i = 0; i < lineItems; i++)
{
int inventoryNumber = 0;
inventoryNumber = getRandom(1, 10);
pickList[i] = inventoryNumber;
for (int dup = 0; dup < lineItems; dup++)
{
if (pickList[i] == pickList[dup])
{
pickList[i] = getRandom(1, 10);
}
}
}
}
I think there is some in the logic I am not quite catching onto. But I'd like to self array comparison to be contained within each loop that generates a random number.
checking to see if you have like 5 items out of 100 (that is 0-100 possible, pick 5 of them) in a loop like that works pretty well. trying to randomly roll 95 values in 0-100, however, will loop a long time as you keep getting repeats until the whim of the random generator produce the last couple of values, which only have around a 5% chance. Shuffle and deal has a 100% chance of working every time, so it can't get stuck trying to beat the odds. And it avoids having to track and check the values by ensuring that you can't get a repeat to begin with. All around, is the way to do it.