3

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.

lemon
  • 188
  • 6
  • +1 for "Find the number of bits in myint and in int, and then concatenate a bunch of rand() numbers until myint is filled." – max66 Jun 05 '16 at 11:23
  • Possible duplicate of [generate random 64 bit integer](http://stackoverflow.com/questions/8120062/generate-random-64-bit-integer) – WhiZTiM Jun 05 '16 at 11:23
  • See [C++11 Random](http://stackoverflow.com/a/21096340/1621391) – WhiZTiM Jun 05 '16 at 11:26

2 Answers2

7

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().

interjay
  • 107,303
  • 21
  • 270
  • 254
  • 1
    Huh, TIL that the 2nd parameter for the constructor is defaulted to the right thing already. (Just an observation, not critique. I think it's better to make it explicit.) – Baum mit Augen Jun 05 '16 at 11:35
2

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);
Rakete1111
  • 47,013
  • 16
  • 123
  • 162