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 镍氢电池充电器设计实物使用原理
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?