Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers are the same every time function is called

Tags:

c++

random

c++11

The numbers are random every time I run the program, but they stay the same during that same run. I want the numbers to be random every time the function is called. I did seed the generator in main().

    std::random_device device;
    std::mt19937 generator(device());

My function

void takeAssignment(std::vector<Student> &students,
                    const int min, const int max,
                    std::mt19937 e)
{
    std::uniform_int_distribution<int> dist(min, max);
    // all students take the assignment
    for (auto &s : students)
    {
        // random performance
        int score{dist(e)};
        s.addScore(score, max);
        std::cout << s.getName() << "'s score: " << score << std::endl;
    }
}

For example, everytime the function was called with the min as 0 and max as 10, the output of the function printed

Abril Soto's score: 1
Bailey Case's score: 9

during that run.

Putting dist inside the loop didn't work either, the numbers stayed the same.

like image 555
VoidChips Avatar asked May 21 '26 04:05

VoidChips


1 Answers

You're passing generator via call by value, thereby creating a copy with no seed and generating same values. Try passing by reference in function argument: like

std::mt19937& e

like image 115
H S Avatar answered May 22 '26 19:05

H S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!