开发者

Trouble when generating an array of random values

开发者 https://www.devze.com 2023-01-29 13:27 出处:网络
I\'m generating an array of random numbers, between 0 and 2 with this code: for ($j = 0; $j < 60; $j++) {

I'm generating an array of random numbers, between 0 and 2 with this code:

    for ($j = 0; $j < 60; $j++) {
       for ($i = 0开发者_如何学Go; $i < 100; $i++) {
                $value = rand(0,2);
                $DBH->query("INSERT INTO map (x, y, value) VALUES($i, $j, $value);");
    }

And i found and oddity, as you may see here, the rows are random, but they repeat:

22121000210211220022122200120200122000122121
22121000210211220022122200120200122000122121
22121000210211220022122200120200122000122121
22121000210211220022122200120200122000122121
22121000210211220022122200120200122000122121

How can avoid that?


You might want to explicitly seed your generator using srand, e.g. srand(time()) (note that the srand link has a better example of seeding than just using time, depends on how random you need, I suppose).

Failing that

  • You could try using mt_rand with mt_srand
  • You could always use MySQL's rand function to generate the numbers as a workaround.
0

精彩评论

暂无评论...
验证码 换一张
取 消