For loop with random

I'm trying to create a different random name each run in this for loop.
But the name doesn't change, and I don't understand why.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
   int main() {
    	
    	// The loop goes while x < 10, and x increases by one every loop
  for ( int x = 0; x < 10; x++ ) {
    // Keep in mind that the loop condition checks 
    //  the conditional statement before it loops again.
    //  consequently, when x equals 10 the loop breaks.
    // x is updated before the condition is checked.    
    
    	srand ( time(NULL) ); //initialize the random seed
    	string randomName[4] = {"Cake", "Toast", "Butter", "Jelly"};
    	int RandIndex = rand() % 4; //generates a random number between 0 and 3
		
		string dag1Namn1;
		dag1Namn1=randomName[RandIndex];
		cout << dag1Namn1;
		
		cout << x <<endl;
	    }
    	return 0;
    }


result:
Butter0
Butter1
Butter2
Butter3
Butter4
Butter5
Butter6
Butter7
Butter8
Butter9
srand ( time(NULL) ); //initialize the random seed
Seed is a number from where pseudo-random generation starts. So-called "random" numbers are actually result of complex calculations on previous value.

So in your loop you are setting seed each iteration. As time() has 1 second precision, all iteration made in same second will set seed to same number. And computers are fast enough to make thousands of iterations per second. No wonder you have same thing generatin over and over.

You should initiliaze PRNG only once in entire program.
I was wondering if that was the case. Of course I am aware that random is not really random. I moved the init of random to above the start of the loop. Now it workd beautifully. Thank you!
Last edited on
Topic archived. No new replies allowed.