I made this random class so I can use random numbers in my game engine whenever I need, but I'm having a problem with the functions, How I'm I suppose to return R ? (please keep in mind that I'm new to coding in general)
#pragma once
#include <ctime>
#include <random>
using namespace std;
class Random
{
private:
public:
Random() { default_random_engine RandomNumber(time(0));};
int RandomNumber()
{
uniform_int_distribution<int> R();
return = R;
}
float RandomFloat()
{
uniform_int_distribution<float> R();
}
int RandomNumberRange(int Min =0,int Max =0)
{
uniform_int_distribution<int> R(Min,Max);
}
float RandomFloatRange(float Min = 0, float Max = 0)
{
uniform_int_distribution<float> R(Min,Max);
}};
The random number engine is supposed to be reused, but currently you are declaring it as a local variable, which is never used again and destroyed when the constructor exits. Instead, make the default_random_engine
a member of your class.
Then, to get an actual random number from a distribution, you need to call it via its overloaded call operator and pass it the random number engine:
class Random
{
private:
default_random_engine RandomNumber{time(0)};
public:
int RandomNumberRange(int Min =0,int Max =0)
{
return uniform_int_distribution<int>{Min,Max}(RandomNumber);
}
//...
};
There really isn't any reason to return the distribution itself. So I interpreted your question in a way that probably makes more sense.
Also note that the seeding with time(0)
is probably a bad one. But this is a huge topic itself. In particular, if you happen to create multiple instances of the Random
class in short succession, they will be equally seeded. Instead
default_random_engine RandomNumber{std::random_device{}()};
may work better. It will probably use random numbers provided by the system. (But it may not, for example older versions of MinGW did generate deterministic results this way.)
int RandomNumber()
{
uniform_int_distribution<int> R();
return = R;
}
Return type and the type of R
in the above function are different. R
is of type uniform_int_distribution<int>
whereas return type is just int
.
To return R()
you have to change the function return type.
uniform_int_distribution<int> RandomNumber()
{
uniform_int_distribution<int> R;
return R;
}
Note that it is not return = R
. return
is a keyword and not a variable that you can assign to. To return a variable just use return R;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With