hi
i want to generate non repeated random numbers many times. for that i m using the following code.

#include "sys/types.h"
#include "stdio.h"
#define MAX 200
#define N 20
main()
{
	int array[N],r;
	int n = 0; int count_check,count_gen ,i,j;

	for(j=0;j<10;j++,printf("\n"))
	{
		srand(j);
		  for (count_gen=0;count_gen<=MAX;count_gen++)
		  {
		    r = rand()%N;
		    for ( count_check = 0; count_check < n; count_check++ )
		    {
		      if ( r == array[count_check] )break;
		    }// end for count_check.
		  if ( count_check == n ) array[n++] = r;
		  }// end for count_gen.
		for(i=0;i<N;i++)
		printf("%d\n",array[i]);
	}// end for j.

}//  end of main.

<< moderator edit: added [code][/code] tags >>

it generates random numbers from 0 to 20 without repeating in an array. but it generates only once. next time in the for loop ( in j ) it gives the same pattern again , which i dont want. can some body please help me to get different pattern every time in the for loop ( for j ).

Dani AI

Generated

Immediate diagnosis: two separate issues produce identical output across the outer loop. The PRNG is being restarted with the same seed each iteration, which makes the generator replay the same sequence every time. Also, the insertion counter that tracks how many unique values have been stored is not reset between iterations, so after the first pass the array is effectively full and subsequent passes just print the same contents. That explains why ’s advice to seed once looked like it “did not work” for — seeding is only one piece; the per-pass state must be reinitialized or advanced.

Practical fixes: seed the PRNG once (with a time-based or otherwise varying seed if different program runs are desired) and do not reseed inside the outer loop. At the start of each outer iteration reset the fill index (and/or reinitialize the array) so each pass begins fresh. If many independent permutations are needed in the same run, either let the PRNG continue (draw the next N numbers without reseeding) or explicitly create a fresh permutation each pass.

A robust, efficient approach is to produce a true permutation instead of sampling-with-rejection. Fisher–Yates (Knuth) shuffle runs in O(N) and guarantees no repeats:

int arr[N];
for (i = 0; i < N; ++i) arr[i] = i;

/* shuffle */
for (i = N - 1; i > 0; --i) {
    j = rand() % (i + 1);
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

/* arr now contains a random permutation of 0..N-1 */

Notes and caveats: rejection sampling gets slow as the set fills; rand()%k has small bias for some uses; for higher-quality randomness or multithreaded code prefer C++11’s <random> (std::mt19937 + std::uniform_int_distribution / std::shuffle). For reproducibility, record and log the seed as suggested. For background on PRNG properties see the standard PRNG references mentioned earlier in the thread.

Recommended Answers

All 7 Replies

Call srand once in a program, before the loop.

Call srand once in a program, before the loop.

I have tried that but it does not work. it produces same pattern of numbers.


regards
shashi

Read this on random numbers

I have tried that but it does not work. it produces same pattern of numbers.

Using the same seed will produce the same pattern. Often srand(time(NULL)); is used, but read the link prog-bman posted.

Hi frnd i am sivaram,
first you include these header files include<time.h>,include<stdlib.h>
and then in main() you put "srand(time(NULL));" after your initializations and before rand(); function every time you will get different output

commented: Gee, I wish someone mentioned that back in 2005... -3

Hi frnd i am sivaram,
first you include these header files include<time.h>,include<stdlib.h>
and then in main() you put "srand(time(NULL));" after your initializations and before rand(); function every time you will get different output

I generally don't like to do this, exactly because you get a "completely" random sequence each time.

Random number generators generally start at a number and then move through a sequence of other (seemingly) random numbers. However, the list of numbers that you get is determined by the initial number. There is a different sequence generated for each starting point.

When working with random numbers, most of the time you are going to want to try and reproduce the results a number of times, for debugging and such if nothing else. If you use the method suggested above, you won't be able to do this, since you won't ever know what the starting point was, and so will never be able to retrace the path that the random number generator takes. My advice would be to either always use the same seed (so you get the same (random-looking) path from the generator) or, if you must use a different sequence each time, at least write the results to a file and get the program to output the seed that was used and store it in the file. In either case, srand(time(NULL)) is never going to be good, since you can't possibly recover the seed. If you have to generate a seed this way, do:

unsigned seed = time(NULL);
srand(seed);

That way, you can write the seed to file with the results of your program later and you have a chance at reproducing the results if you need to.

EDIT: Sorry, just noticed that this thread is from 2005. My bad. It should probably be closed or something!

Yes all you need to do is use
srand(time(NULL));

but make sure to add
# include <time.h> and # include <stdlib.h>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.