Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ random number for arbitrary integer (of fundamental type)

I have a typedef for some arbitrary integer type, e.g.

typedef unsigned long long myint;

in other words, I don't know how it's actually defined, but I can guarantee that it's a fundamental type.

I also have a variable instance of this type

myint n;

How do I assign n a random value that could be any value supported by myint?


Simply scaling the result of rand() to cover the range of myint would not be suitable since myint will likely be larger than the int type and therefore there will be inaccessible numbers.

Something like the following would work but seems rather inelegant and inefficient: Find the number of bits in myint and in int, and then concatenate a bunch of rand() numbers until myint is filled.

like image 951
lemon Avatar asked Jan 26 '26 07:01

lemon


2 Answers

With the C++11 <random> library, uniform_int_distribution can give you any integer type:

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<myint> dis(
    std::numeric_limits<myint>::min(), 
    std::numeric_limits<myint>::max());

myint num = dis(gen);

With unsigned types you can use the default constructor for uniform_int_distribution, which gives the range 0 to numeric_limits<T>::max().

like image 108
interjay Avatar answered Jan 28 '26 19:01

interjay


Use the #include <random> library functions!


As a bonus, those functions guarantee that the integers will be uniformly distributed across the given range.

//Initialize random engine
std::random_device rd;
std::mt19937 mt{ rd() };
std::uniform_int_distribution<myint> uid; //Default constructor - Range is 0 to myint-max

//'num' is random!
myint num = uid(mt);
like image 42
Rakete1111 Avatar answered Jan 28 '26 20:01

Rakete1111



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!