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 post
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 post

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • 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.