KingJohnno
KingJohnno

Reputation: 602

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.

Upvotes: 4

Views: 3685

Answers (4)

hansmaad
hansmaad

Reputation: 18905

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, " "));
}

Upvotes: 0

zakinster
zakinster

Reputation: 10688

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.

Upvotes: 1

Jepessen
Jepessen

Reputation: 12415

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.

Upvotes: 3

Pete Becker
Pete Becker

Reputation: 76245

Call srand exactly once, usually early in the code in main.

Upvotes: 6

Related Questions