dqrsceg6279196 2016-05-13 16:45
浏览 273
已采纳

在php中生成2个数字范围的随机数

My current code generates 116 random numbers between the range of 34 and 76 and puts them into an array called $common.

for($i = 0; $i < 116; $i++){
    $common[] = mt_rand(34, 76);
}

Is it possible to generate a random number from 2 groups of numbers? For instance, I want to have it pick 116 random numbers between 1-22 and 34-76.

  • 写回答

1条回答 默认 最新

  • doushi1996 2016-05-13 16:51
    关注

    1. Here's one way:

    for($i = 0; $i < 116; $i++){
        $common[] = array(mt_rand(1, 22), mt_rand(34, 76))[mt_rand(0, 1)];
    }
    
    • Create an array of two random numbers, one from each range
    • Randomly pick array index 0 or 1

    2. Well I'm bored, here's another:

    $range = array_merge(range(1, 22), range(34, 76));
    
    for($i = 0; $i < 116; $i++){
        $common[] = $range[array_rand($range)];
    }
    
    • Create an array of the numbers in the two ranges
    • Loop and randomly select from the range

    In the second example you can also use:

    $common[] = $range[mt_rand(0, count($range)-1)];
    

    3. I'm waiting for lunch so here's another, similar to the first:

    for($i = 0; $i < 116; $i++){
        $common[] = mt_rand(0, 1) ? mt_rand(1, 22) : mt_rand(34, 76);
    }
    
    • If random falsey 0 then generate from the first range
    • If random truthy 1 then generate from the second range
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题