0

I'm trying to populate a simple array in C++ using a function that generates random numbers within a given range. For whatever reason it is giving me the same random number for each element. I think the problem has something to do with where I'm seeding the random variable.

Any ideas?

#include <iostream> // for user input/output
#include <cstdlib> // for rand/srand functions
#include <ctime> // for time usage
using namespace std;

const int SIZE = 10;
const int MIN = 100;
const int MAX = 200;

int main()
{

 int Arr[SIZE];

 for (int i = 0; i < SIZE; i++){
   Arr[i] = rng(MIN, MAX);

 }

  for (int j = 0; j < SIZE; j++){

    cout << Arr[j] << " ";

  }
}

int rng(int lo, int hi){

  static bool variable;

  variable = false;

  if (variable == false){
    srand(time(0));
    variable = true;
    }

  return rand() % (hi - lo + 1) + lo;

  }
Afshin
  • 8,839
  • 1
  • 18
  • 53
Jerry123
  • 67
  • 8
  • 1
    `srand(time(0));` only once. – Jarod42 Jul 13 '21 at 15:39
  • 1
    btw, [``](https://en.cppreference.com/w/cpp/numeric/random) has better alternative. – Jarod42 Jul 13 '21 at 15:40
  • 1
    Just call `srand(time(0));` once *only* at the beginning of the program. Preferably in `int main()` – Galik Jul 13 '21 at 15:40
  • 1
    You reset the random seed each time you call `rng`, leading to the exact same number being generated (if called in the same second). C++ have [a very good random number generation library](https://en.cppreference.com/w/cpp/numeric/random) beyond those two old C functions. For example [`std::uniform_int_distribution`](https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) which seems to be a very good match to what you want. – Some programmer dude Jul 13 '21 at 15:40
  • 1
    `static` variable is indeed shared between function calls and indeed only initialized once, but you overwite its value with every call, which means it's useless. Initialize it correctly, and then you will only call `srand` once - `static bool variable = false;` – Yksisarvinen Jul 13 '21 at 15:51

1 Answers1

1

As mentioned in comments, you need to call srand(time(0)); only once, just call it at start of main().

The reason is that rand() itself is just a pseudorandom generator (a simple LFSR in a lot of cases) based on its starting seed. if you reseed algorithm with same number, you will get similar sequence of number from it, so your array will be filled with similar set of numbers.

In addition, it is better to use C++ random generator.

Afshin
  • 8,839
  • 1
  • 18
  • 53
  • Sorry that second srand was included as an error. I removed it, tried moving the srand into int main() before each array assignment, and its still populating the array with the same number – Jerry123 Jul 13 '21 at 15:44
  • 1
    @Jerry123 you need to remove both from `rng()` and just add ` at start of `main()`. – Afshin Jul 13 '21 at 15:46