-2

I wanted to create a separate function inside my ff class to generate a random number and return that number. The function seems to work perfectly when used outside a loop. However, when I put the function inside a loop, it keeps generating the same number even though I am calling the random function each time! What exactly am I doing wrong?!

  //return a random number
  int ff::random_number() const
  {
      srand((unsigned)time(NULL));
      return (rand() % 20 + 1); //in the range of 1 to 20
  }


  //creates an int list of random size and random elements
  int ff::create_random_list()
  {
      list_length = random_number(); //the list size
      list_of_numbers = new int[list_length]; //initilize the list

      for (int i = 0; i < list_length; ++i)
          list_of_numbers[i] = random_number(); //insert a random number

      return 1;
  }
  • Note: I've checked all similar questions that were posted before this question, but nothing answered my question. Just to be clear.
BAS
  • 145
  • 1
  • 11
  • @Sneftel This is useful but not fair to call it an exact duplicate! – BAS Jun 12 '17 at 09:47
  • i assume that (unisgned)time(NULL) return the same value inside loop, so you set pseudo random numebr generator to the same state on each loop iteration, and it gives you the same pseudo random number each time (as expected) – Andrew Kashpur Jun 12 '17 at 09:48

1 Answers1

1

You have to seed the function once, not every time (which happens when you use your function inside a loop).

So this line:

srand((unsigned)time(NULL));

should be executed once.

gsamaras
  • 71,951
  • 46
  • 188
  • 305