Call srand
exactly once, usually early in the code in main
.
C++ random number generator
سؤال
I am writing an lottory application. I have a function called generateLotteryNumbers
this takes in an array and fills that array with 5 random numbers. What I want to do is have this function produce a different set of random numbers every time this function is called.
void generateLotteryNumbers(int lotteryNumbers[])
{
srand (time(NULL));
const int arraySize = 5;
int index = 0;
while (index < arraySize)
{
lotteryNumbers[index] = rand() % 50 + 1;
cout << lotteryNumbers[index] << endl;
index++;
}
}
The output at the moment is eg:
5
24
45
26
47
Repeated twice.
المحلول
نصائح أخرى
Width C++11 standard, you can use new number generators. To obtain always different results, usually you must set a different seed at every program execution, for example with time.
You may take a look at the c++11 features that provide better pseudo-random number generator (e.g. Mersenne Twister ) as well as a random_device
interface that may be used for seeding the generator with an hardware entropy source.
Example with std::vector
and c++11 <random>
features:
vector<int> generateLotteryNumbers(int size)
{
static std::random_device rseed;
static mt19937 rgen(rseed());
uniform_int_distribution<int> idist(1,50);
vector<int> result;
for(int i = 0; i < size; ++i) {
result.push_back(idist(rgen));
cout << result[i] << endl;
}
return result;
}
Also note that if you're generating lottery numbers, you may not want the same value twice in the same array, in which case, you'll have to add a bit more logic to your code.
You should not call srand
multiple times. Furthermore you should not use rand
this way to generate lottery numbers (ok, depends on the lottery but I think duplicate numbers are not allowed). You can do it very easy using std::random_shuffle
int main()
{
int numbers[49]; // all numbers
std::iota(begin(numbers), end(numbers), 1); // fill with 1-49
// shuffle numbers
std::random_shuffle(begin(numbers), end(numbers));
// use first 5 numbers:
std::copy(begin(numbers), begin(numbers) + 5,
std::ostream_iterator<int>(std::cout, " "));
}