Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations waross on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

random numbers

Status
Not open for further replies.

pplrose

Computer
Nov 18, 2002
3
0
0
US
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?
 
Replies continue below

Recommended for you

I have a random lotto number generator I created a few years ago, written in Borland.

I'm a bit rusty on C++ at the moment but I can pull it out and get back to you if you wish.
 
rand() is the c function that will generate your random numbers; simply include <stdlib.h>, seed your generator with srand(12345), and successive calls to rand() will return an integer in the range [0,RAND_MAX]. To scale that back to the range you want (e.g. if you want numbers between 1-100) you normalize, scale, and translate, e.g.

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: &quot;random&quot; list of non-repeating numbers, 1-100


Hope that helps,
/m
 
Here's a few functions you might like to try:

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
 
Status
Not open for further replies.
Back
Top