0

I'm trying to write a piece of code that goes through a random element of a string array and then outputs it. After it outputs it then sets that element to 0. And then that if statement ensures that name will not be outputted again.

void group(){  
  int random =  rand() % 50;
  int i, j = 0;
  while(j<50){ 
    srand(0);
    random =  rand() % 50; 
    groupNum = 1;
    cout << "Group " << groupNum << " has: ";
    if(names[random] != "0"){ 
      cout << names[random] << " "; 
    names[random] = "0"; 
    j++;
    }  
    if(names[random] == "0"){ 
      continue;
    }
    i++; 
    if(i == peoplePerGroup){ 
      groupNum++; 
      cout << "\n\n"; 
      i=0;
      }
    } 
  }  
Oliver
  • 13
  • 1

2 Answers2

0

srand function (as a pseudo-random number generator) should only be seeded once, before any calls to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.

"In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header ). This is distinctive enough for most trivial randomization needs."

Also, every time your function runs, it's get a random element of your array and sets it to zero. The only way this loop ends is in a scenario that every single elements on this array were setted to zero. Buy in each loop, the index choosed is random. Think about how many times they need to run until they fill your requirements.

Matheus Martins
  • 161
  • 1
  • 10
0

As a little explanation to why the re-seeding with the same number causes this issue: rand() uses pseudo-randomness and therefore it is reproducable. Basically it meshes up some internal number that is set based on the seed. The number for example has bitwise XOR ( ^ ) applied to a constant etc. After every call, the number is also incremented internally. Naturally that means that with the same starting number (aka the seed) you get the same results every time.

By the way, your whole code becomes much smoother if you fill all your words into an std::set and remove the word from the set when taking it, instead of setting it to null. See here: How to select a random element in std::set?

Or even easier, fill them into a vector and apply: std::random_shuffle Then just iterate through that vector a single time to receive the words in random order.

AlexGeorg
  • 967
  • 1
  • 7
  • 16