random numbers
random numbers
(OP)
I would like to make a string or array of numbers, have them be random and not repeated. What would be the best way to do this?
INTELLIGENT WORK FORUMS
FOR ENGINEERING PROFESSIONALS Come Join Us!Are you an
Engineering professional? Join Eng-Tips Forums!
*Eng-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail. Posting GuidelinesJobs |
|
RE: random numbers
RE: random numbers
RE: random numbers
RE: random numbers
I'm a bit rusty on C++ at the moment but I can pull it out and get back to you if you wish.
RE: random numbers
As for the not repeated part, I suggest using the STL class set<>.
RE: random numbers
RE: random numbers
ValueOneToHundred = ((double)rand() / RAND_MAX) * 99 + 1; // returns random integer between 1 and 100
Making sure you don't repeat numbers is a little more tricky. A simple way would be to check for each new number whether you've used it before, but that is slow.
Better solution for your problem might be filling your array in order, then doing a random sort operation on it. A simple one would be:
1) fill array with 100 sequential numbers, 1-100
2) pick two indices at random and swap the values
3) repeat until you feel satisfied
Result: "random" list of non-repeating numbers, 1-100
Hope that helps,
/m
RE: random numbers
static const int A = 14287;
static const int M = 3676253437;
static const int Q = M / A;
static const int R = M % A;
// Construct with Value for the state.
Random::Random( int Value )
{
if( Value < 0 )
Value = Value * (-1);
state = Value;
if( state == 0 )
state = 1;
}
// Return a pseudorandom int, and change the
// internal state.
int Random::randomInt( )
{
int tmpState = A * ( state % Q ) - R * ( state / Q );
if( tmpState >= 0 )
state = tmpState;
else
state = tmpState + M;
return state;
}
// Return a pseudorandom double in the open range 0..1
// and change the internal state.
double Random::random0_1( )
{
return (double) randomInt( ) / M;
}
// Return an int in the closed range [low,high], and
// change the internal state.
int Random::randomInt( int low, int high )
{
double partitionSize = (double) M / ( high - low + 1 );
return (int) ( randomInt( ) / partitionSize ) + low;
}
Have fun!
Derrick