1

i have strange behavior in which i try to generate random numbers and they sometimes totally the same , or there is problem if they created on the same time? using VC 2012

for (int i = array_size; i < (array_size); i++)
{

        srand((unsigned int)time(NULL));
        int rw = rand() % 960 + (20); //returns a pseudo-random integer between x resolution size 0 -> width
        int rh = rand() % 640 + (20);    //returns a pseudo-random integer between x resolution size 0 -> height
        lwsl_notice("c:%d width %d height %d\n",c, rw, rh);
        c++;
}

The output is :

[2016/06/30 09:39:09:7274] NOTICE: c:0 width 606 height 567
[2016/06/30 09:39:09:7274] NOTICE: c:1 width 606 height 567
[2016/06/30 09:39:09:7274] NOTICE: c:2 width 606 height 567
[2016/06/30 09:39:09:7274] NOTICE: c:3 width 606 height 567
user63898
  • 29,839
  • 85
  • 272
  • 514
  • You should use `srand` outside the loop and once. – ameyCU Jul 30 '16 at 06:46
  • 1
    oops the more correct dup is [Same random numbers every loop iteration](http://stackoverflow.com/q/9251117/995714), [rand() is consistent across multiple function calls](http://stackoverflow.com/q/29478555/995714), [srand(time(NULL)) doesn't change seed value quick enough](http://stackoverflow.com/q/5574914/995714), [srand() — why call it only once?](http://stackoverflow.com/q/7343833/995714) – phuclv Jul 30 '16 at 06:54

3 Answers3

5

Move srand((unsigned int)time(NULL)); out of the for loop.

artm
  • 17,291
  • 6
  • 38
  • 54
3

Your loop is so fast that time(NULL) always have the same value. This means that your generator always starts from the same seed, so it will always generate the exact same values.

srand should be called once and only once in your program (outside the for loop). Commonly, people call it once from themain function.

jpo38
  • 20,821
  • 10
  • 70
  • 151
1

Inside for loop you initialized i as array_size and you are looping it till i<array_size with incrementing i. Whats that? Please post some more code.

  • That's not an answer – jpo38 Jul 30 '16 at 06:54
  • it's **without** incrementing `i` and the loop won't execute a single time. Anyway that's not the main problem here because even if the OP fixes the loop it won't work anyway – phuclv Jul 30 '16 at 06:59