Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernize random generation #124

Closed
bodand opened this issue Oct 6, 2020 · 0 comments · Fixed by #127
Closed

Modernize random generation #124

bodand opened this issue Oct 6, 2020 · 0 comments · Fixed by #127

Comments

@bodand
Copy link
Contributor

bodand commented Oct 6, 2020

In a lot of places, the project uses the C rand() function, even though the project itself is C++11, which has the "new" and fancy <random> header.
C++11 and up projects should always use <random> and one of its PRNGs instead of the severely limited C random functions, whose actual randomness is really platform-dependent and will work differently across libc implementations. Also using modulo to calculate a distribution skews the results. See this talk from STL, in which he describes why rand() is bad. (And also how to use the C++11 <random> header.)

I suggest a small random wrapper function be made that takes a min and max and generates a random number within those. Something like this:

int random_int(int min, int max) {
    static std::mt19937 rng(std::random_device{}());
    std::uniform_int_distribution<int> dist(min, max);

    return dist(rng);
}

And then use this function in all places where randomness is needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants