duangan6731 2014-10-01 09:21
浏览 327
已采纳

生成从10000000到99999999的唯一随机数

I need to create unique random pins using numbers only. I need to produce between 10,000,000 and 99,999,999. I need to create 100,000 pins

Here's the code I am currently using:

function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $quantity);
}
print_r( UniqueRandomNumbersWithinRange(10000000,99999999,100000));

This code still runs okay with my server using 50000 but not with 100000 items. Can you help me, is there code that can produce this many unique numbers without using too much memory in the server?

  • 写回答

3条回答 默认 最新

  • dounuo7954 2014-10-01 09:32
    关注

    I believe this should do the trick for you:

    <?php
        function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
            $i = 0;
            $numbers = array();
            while( $i <= $quantity ){
                $numbers[$i] = mt_rand($min, $max);
                $i++;
            }
            print_r( $numbers );
        }
        UniqueRandomNumbersWithinRange(10000000,99999999,100000);   
    ?>  
    

    As of the comment to my answer, there is a posibility of multiple keys containing the same pin. This code will eliminate duplicates, but takes a lot more computing time:

    <?php
        function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
            $i = 0;
            $numbers = array();
            while( $i <= $quantity ){
                $number = mt_rand( $min, $max );
                if( !in_array( $number, $numbers ) ){
                    $numbers[$i] = $number;
                    $i++;
                }           
            }
            print_r( $numbers );
        }
        UniqueRandomNumbersWithinRange(10000000,99999999,100000);   
    ?>  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证