#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.
*/
#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.
*/