GETRANDOM(min,max)((rand()%(int)(((max)+1)-(min)))+(min)) How in C#

  • Thread starter Thread starter Roy Gourgi
  • Start date Start date
R

Roy Gourgi

Hi,

What is the equivalent code in C# of these 2 statements in C++.

GETRANDOM(min,max)((rand()%(int)(((max)+1)-(min)))+(min)); // C++ code
srand( (unsigned)time( NULL ) ); // C++ code

TIA

Roy
 
So would this do the trick?

public class cGetRandom

{

static Random rand = new Random();

private static int GetRandom()

{

lock ( rand )

{

return rand.Next();

}

}

}

Thanks

Roy
 
The .NET Framework provides a pretty good random number generator... to use
it similar to the one you used in C++, try doing the following:

Random rand = new Random(0);
rand.Next(min, max);

Brendan
 
Brendan Grant said:
The .NET Framework provides a pretty good random number generator... to use
it similar to the one you used in C++, try doing the following:

Random rand = new Random(0);
rand.Next(min, max);

I think you want to use this constructor instead:

Random rand = new Random();

THe one you are provided passes the same seed every time, the parameterless
one uses the systemclock to seed the generator.
 
Hi,

What is the equivalent code in C# of these 2 statements in C++.

GETRANDOM(min,max)((rand()%(int)(((max)+1)-(min)))+(min)); // C++ code
srand( (unsigned)time( NULL ) ); // C++ code

TIA

Roy

In addition to the others advice it should be mentioned that the
Random object is seeded in its constructor. It is therefore a good
idea to only create one instance of the Random class. A common
beginner's mistake is to do this

private static int GetRandom()
{
Random rand = new Random();
return rand.Next();
}

This method could return the same number several times in a row since
the constructor is seeded by the current timestamp. The correct way is
to do it like this

static Random rand = new Random();
private static int GetRandom()
{
return rand.Next();
}
 
Marcus said:
In addition to the others advice it should be mentioned that the
Random object is seeded in its constructor. It is therefore a good
idea to only create one instance of the Random class. A common
beginner's mistake is to do this

private static int GetRandom()
{
Random rand = new Random();
return rand.Next();
}

This method could return the same number several times in a row since
the constructor is seeded by the current timestamp. The correct way is
to do it like this

static Random rand = new Random();
private static int GetRandom()
{
return rand.Next();
}

Also, I would advise wrapping any calls to the static Random object
with a lock, because as far as I'm aware Random does not claim to be
thread-safe:

private static int GetRandom()
{
lock ( rand )
{
return rand.Next();
}
}



Matt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top