Jump to content

[C++11] number_ex fix


Recommended Posts

  • VIP

Hi all!

This is recommended for those who are testing or running on windows.

The reason for the error is that they have a 100% chance of dropp.

 

Based on the video, you can watch:

 

number_ex old version:

https://vimeo.com/user97154960/review/493139410/67f238afc3

https://imgur.com/XExy5kl

 

number_ex fixed:

https://vimeo.com/user97154960/review/493139336/6deedf5e92

https://imgur.com/3BMsyi6

 

FIX:

#include <random>

int number_ex(int from, int to, const char* file, int line)
{
    if (from > to)
    {
        int tmp = from;

        sys_err("number(): first argument is bigger than second argument %d -> %d, %s %d", from, to, file, line);

        from = to;
        to = tmp;
    }

    int returnValue = 0;

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distrib(from, to);

    if ((to - from + 1) != 0)
        returnValue = distrib(gen);
    else
        sys_err("number(): devided by 0");

    return returnValue;
}

 

Edited by flatik
add videos
  • Love 7

c++latest, latest libs...

Link to comment
int number_ex(int from, int to, const char *file, int line)
{
	// We only need (and want) to initialize the mersenne twister generator once
	static std::random_device rd;
	static std::mt19937 mt(rd());
	static std::uniform_int_distribution<int> dist; // not too expensive to create, though

	if (from > to)
	{
		int tmp = from;

		sys_err("number(): first argument is bigger than second argument %d -> %d, %s %d", from, to, file, line);

		from = to;
		to = tmp;
	}

	// Set the range we'd like our distribution to be on, and generate the number
	return dist(mt, std::uniform_int_distribution<int>::param_type(from, to));
}

 

Edited by Etzhel
  • Love 1
  • Good 1
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×
×
  • Create New...

Important Information

Terms of Use / Privacy Policy / Guidelines / We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.