Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

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

random numbers from a ranged integers 1

Status
Not open for further replies.

fcsohn

Programmer
Dec 26, 2004
3
KR
#include <iostream>
#include <iomanip>
#include <time.h>
#include <stdlib.h>

/*
from numbers of 1 to max, get nrand random numbers,
each of which is different from others */

void get_random_numbers( int* rnums, int nrand, int max )
{
int i, ir;
int* numbers = new int[max];

if( numbers == 0 )
{
cerr << " Unable to Allocate Memory for numbers." << endl;
exit( EXIT_FAILURE );
}

srand( (unsigned)time(NULL) );
for( i = 0; i < max; i++ )
numbers = i+1;

for( i = 0; i < nrand; i++ )
{
ir = rand() % max;
rnums = numbers[ir];
numbers[ir] = numbers[--max];
}
delete[]numbers;
}

int main(void)
{
int i, j, n = 100;
int randoms[5];

/*
make 100 instances of 5 different random
numbers selected from 1 to 10 */

for( i = 0; i < n; i++ )
{
get_random_numbers( randoms, 5, 10 );

// view the result from above
for( j = 0; j < 5; j++ )
cout << setw(3) << randoms[j] << " ";
cout << endl;
}
return 0;
}

/*
For the above C++ source,
when debugging in step by step mode, it creates differenct instances as I intended.
But in real time execution, it creates almost same one instance of 5 diffreent random numbers from 1 to 10

I Wonder what's wrong?
I guess it is something related to random number generator.
But I am not sure...

Please advise me to fix it or introduce me a reliable function if any that returns certain number of random numbers from a ranged values.

Thank you for your attention.
*/






 

Just a shot in the dark. Maybe, due to the speed of your computer, the resolution of the time() function is too coarse. In the step-by-step mode you give the time() function time to change. But in the compiled run mode it does the calculations fast enough to have the same srand(). Try putting a 100ms delay in your main function between calls to get_random_numbers().



HyperEngineer
If it ain't broke, it probably need improvement.
 
> srand( (unsigned)time(NULL) );
Do this exactly ONCE at the start of your program, not every time your function is called.

Time is effectively a constant in a short-lived program such as this, so all you're doing is resetting the random number generator back to the same point each time.



--
 
Thank you very much for your useful adivice, Salem!
Turned out OK!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top