I'm trying to write a program to generate random number, within a range of predetermined numbers, while not having any duplicate numbers.
for instance:
I need 5 (non duplicate) numbers, between 1 and 10.
I tried using Rand, and then looping to regenerate number that were duplicated. But, that sat there running for about an hour, and never got all the numbers to be unique.
Any help on this would be greatly appreciated.
Thanks in Advance,
-Charles...
Need help with a C++ number generator problem?
Create a boolean array of 11 elements and initialise all the elements to false.
Now get a random number between 1 and 10
check the array [randomNumber] to see if you have that number (false means the number has not been used yet).
Now set array [randomNumber] to true.
If you have already had that number then get another random number.
You can either do something with the numbers when you first know that they have not been used or you can use the array to list the numbers in sequence.
Reply:I'm not using C++ these days.
Did you look at Linux kernel's random number generator? It is a popular method. I haven't studied it yet.
Reply:well I'd say make a class for random generators.
The class has "boxes" for each number via an array.
Now
array[i] contains i, but, when array[i] is chosen, you switch it with the last value in the array, then % by one less, so that part of the array isn't a choice, it'd be a memory hog for huge number sets though.
Reply:oh try this link, maybe a solution.
http://www.daniweb.com/forums/thread7541...
thanks
Reply:C++ isnt my area, but i hope this i found on the internet helps
Good luck!
http://www.tutorialized.com/view/tutoria...
and put an if in to match each one of the results and if they match start again
i do this in visual basic, and it doesnt take an hour to get unique numbers
Reply:I don't know what your code is, so I can't tell you what's wrong with it. When I wrote this code, I didn't run into the problem of it hanging. It takes... well, it seems "instant." Try this:
####### CODE #######
#include %26lt;iostream%26gt;
using namespace std;
#define howMany 5
#define low 1
#define high 10
bool in_array(int num, int *array)
{
for (int i = 0; i %26lt; howMany; i++)
{
if (array[i] == num)
return true;
}
return false;
} // end in_array()
int main(int argc, char *argv)
{
srand(time(NULL));
int currentNum;
int nums[howMany];
for (int i = 0; i %26lt; howMany;)
{
currentNum = (rand() % (high - low + 1)) + low;
if (!in_array(currentNum, nums))
{
nums[i++] = currentNum;
cout %26lt;%26lt; currentNum %26lt;%26lt; "\n";
}
}
return 0;
} // end main()
####### END CODE #######
I wrote this so you can specify you high and low values (inclusive) and how many unique numbers you want from that range.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment