Chandan Shetty SP
Chandan Shetty SP

Reputation: 5117

Random number generation

I am using below code to generate random numbers in range...

int randomNumberWithinRange(int min,int max)
{
        int snowSize = 0;
        do
        {
            snowSize = rand()%max;
        }
        while( snowSize < min || snowSize > max );
        return snowSize;
    }

for(int i = 0; i < 10 ; i++)
  NSlog("@"%d",\t", randomNumberWithinRange(1,100));

If I quit my application and restart, same set of numbers are generated. How to generate different set of random numbers for every launching.

Upvotes: 4

Views: 1401

Answers (6)

Software_Designer
Software_Designer

Reputation: 8587

This code generates a unique random number only once.

#include <ctime>
# include <iostream>
using namespace std;


int main()
{

      int size=100;
      int random_once[100];
      srand(time(0));

      for (int i=0;i<size;i++)  // generate unique random number only once
      {
          random_once[i]=rand() % size;
          for(int j=0;j<i;j++) if (random_once[j]==random_once[i]) i--;   
      }

      for ( i=0;i<size;i++) cout<<" "<<random_once[i]<<"\t";

  return 0;

Upvotes: 0

Jasarien
Jasarien

Reputation: 58448

You should consider using arc4random instead of rand, for many reasons, one of which is arc4random doesn't require seeding.

Upvotes: 3

frankc
frankc

Reputation: 11473

In addition to seeding the random number generator with srand(), your general technique here is not quite right. First of all you should never use modulus for cutting the rand range. This users lower-order bits which are less random. Second, there is no need to loop. You can get the range directly. Here is how to do it:

snowSize = min + (int) (max * (rand() / (RAND_MAX + 1.0)));

Upvotes: -1

Danvil
Danvil

Reputation: 22991

You have to initialize the random number generator with a seed as pointed out.

Additionally you should avoid the loop:

int randomNumberWithinRange(int min,int max)
{
  return min + rand() % (max - min + 1);
}

Upvotes: 4

RC.
RC.

Reputation: 28207

You need to seed the random number generator.

From the man page:

The srand() function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand() is called before any calls to srand() are made, the same sequence shall be generated as when srand() is first called with a seed value of 1.

Upvotes: 3

phimuemue
phimuemue

Reputation: 35983

Do something like for example srand(time(NULL)), i.e. sync it with time (in the initialisation of your program, of course).

Upvotes: 11

Related Questions