Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeated values from std::uniform_int_distribution

Tags:

c++

random

c++11

I don't understand what's going on here.

#include <iostream>
#include <random>
#include <chrono>
using namespace std;

unsigned number_in_range(unsigned, unsigned, default_random_engine);

int main()
{

    time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());

    default_random_engine rng(now);

    //
    // Print out 10 random numbers
    //
    for (int i = 0; i < 10; i++)
    {
        uniform_int_distribution<int> dist(0, 100);
        cout << dist(rng) << endl;
    }

    cout << endl;

    //
    // Do the same thing, but get the numbers from `number_in_range()`
    //
    for (int i = 0; i < 10; i++)
    {
        cout << number_in_range(0, 100, rng) << endl;
    }

    return 0;
}

unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine rng)
{
    uniform_int_distribution<int> dist(range_start, range_end);
    return dist(rng);
}

An example of the output of this code is:

45
21
10
3
54
18
23
72
68
27

68
68
68
68
68
68
68
68
68
68

number_in_range() works in exactly the same way as the code in my first for loop, and yet it spits out the same value over and over again. What's different about the number_in_range() version, and how can I fix it?

like image 966
Michael Dorst Avatar asked Dec 11 '22 12:12

Michael Dorst


1 Answers

You are copying the random engine instead of taking a reference to it. Hence, it always has the same internal state.

Try:

unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine &rng)
like image 72
Rémi Bonnet Avatar answered Jan 07 '23 15:01

Rémi Bonnet