We know that to generate random long number we do following steps in Java
Random r=new Random()
return r.nextLong();
what will be equivalent of this code in C++? like this?
return (long) rand();
We know that to generate random long number we do following steps in Java
Random r=new Random()
return r.nextLong();
what will be equivalent of this code in C++? like this?
return (long) rand();
Portable hack:
long r = 0;
for (int i = 0; i < sizeof(long)/sizeof(int); i++)
{
r = r << (sizeof(int) * CHAR_BITS);
r |= rand();
}
return r;
Why do you need a random long anyway?
Using boost random library can save you of quite nasty surprises with (pseudo)random numbers
First, you have ton know that in the current standard C++ there is no random library. In fact there is one, but it's available in a sperate namespace called TR1 because it's the result of a Technical Report done in 2003. It will be available in the standard library for the next standard (coming next year if all goes well).
So if you have a recent compiler (VS2008 or lasts versions of GCC) you have access to the std::tr1::random library; If you have a compiler implementing the parts of the next standard, then you have it std::random.
If you don't have access to that library, there is an implementation available in the boost libraries : http://www.boost.org/doc/libs/1_44_0/doc/html/boost_random.html
Now in all cases, the way to get a random number is the same as it's all the same library (from the boost doc):
boost::mt19937 rng; // produces randomness out of thin air
// see pseudo-random number generators
boost::uniform_int<> six(1,6); // distribution that maps to 1..6
// see random number distributions
boost::variate_generator<boost::mt19937&, boost::uniform_int<> >
die(rng, six); // glues randomness with mapping
int x = die(); // simulate rolling a die
<cstdlib> provides int rand(). You might want to check out the man page. If long is bigger than int on your system, you can call rand() twice and put the first value in the high word.
#include <cstdlib>
long lrand()
{
if (sizeof(int) < sizeof(long))
return (rand() << (sizeof(int) * 8)) | rand();
return rand();
}
(it's very unlikely that long is neither the same as or double the size of int, so this is practical if not theoretically perfect)
Check your docs for rand() though. It's not a great generator, but good enough for most things. You'll want to call srand() to initialise the random-number generation system. Others have commented that Windows doesn't return sizeof(int) randomised bits, so you may need to tweak the above.