duanfan1965 2011-10-22 09:48
浏览 52
已采纳

函数生成唯一随机值数组

As Mysql rand() is time consuming I am using alternate way using Mysql max() and PHP. I wrote this code for fetching random product_id's:

function RandomUniqueArray($min,$max,$limit){

    $random_array = array();
    if(isset($limit) && is_numeric($limit)){
        for($i=0;$i<$limit;){
            $rand_val = mt_rand($min, $max);
            if(!in_array($rand_val, $random_array)){
                $random_array[] = $rand_val;
                $i++;
            }
        }
    }
    return $random_array;
}

This works fine as I want each time it gives different result set with different unique values but it takes 6.232 micro seconds. Ohter I got by Google is:

$random_array = array_rand(array_fill($min,$max, true),$limit);

with takes only 0.101 microseconds but its result set is repeated means. Unique values array is fine but whole set is repeated. Why is it so???

I called both of these by one by one as

$random_array = RandomUniqueArray(1,64000,4);

And

$random_array = array_rand(array_fill(1,64000, true),4);

Thank you.

  • 写回答

1条回答 默认 最新

  • dongzhoulong1797 2011-10-22 12:59
    关注

    I made a script,that only takes ̣̣̣+- 4.5E-6.

    Try it.

    function randomValue($min,$max,$limit)
    {
        $array = Array();
        $MAX = mt_rand($min,$max);
        for($i = 0;$i < $limit;$i++)
        {
            $array[$i] = mt_rand($min,$MAX);
            while( is_array($array[$i],$array) ) //To check if exist, if. Make new.
            {
               $array[$i] = mt_rand($min,$MAX);
            }
        }   
        return $array;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。