简体   繁体   English

生成范围内不连续的随机数

[英]Generate non consecutive random numbers within a range

I have the following code我有以下代码

<?php
function randomGen($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    $tmp = array_slice($numbers, 0, $quantity);
    //sort($tmp);
    return $tmp;
}
echo '<pre>';
$arr = randomGen(2,7,5);
//sort($arr);}
print_r($arr);

This code generates random n numbers between the specified range.此代码生成指定范围之间的随机 n 个数字。

However, it returns the output similar to the following many times但是,它多次返回类似于以下的输出

Array
(
    [0] => 3
    [1] => 4
    [2] => 7
    [3] => 5
    [4] => 2
)

Here, 2 3 4 5 are consecutive numbers.这里,2 3 4 5 是连续数。 I am trying to modify the above code so that it does not return more than 3 consecutive numbers.我正在尝试修改上面的代码,使其不返回超过 3 个连续数字。 The output should be similar to this输出应该与此类似

Array
(
    [0] => 2
    [1] => 3
    [2] => 5
    [3] => 6
    [4] => 7
)

As you can see, it has just 3 consecutive numbers 5 6 7.如您所见,它只有 3 个连续的数字 5 6 7。

I have tried the following我已经尝试了以下

<?php

function randomGen($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    $tmp = array_slice($numbers, 0, $quantity);
    sort($tmp);
    return $tmp;
}
echo '<pre>';
$arr = randomGen(2,7,5);
$count = 0;
$first = $arr[0];
$i = 1;
//for($i = 1; $i < count($arr); $i++) {
while ($i < count($arr)) {
    $ele = $arr[$i];
    if ($counter >=3) {
        $counter = 0;
        $arr = randomGen(2,7,5);
        $first = $arr[0];
        $i = 1;
    }
    else {
    if ($ele - $first === 1) {
        $counter++;

        //continue;
    }

    $first = $ele;
}
$i++;
}
print_r($arr);

But it doesn't provide the expected output.但它没有提供预期的输出。

Thanks in advance for any help.在此先感谢您的帮助。

Please see if we can do something like this请看看我们是否可以做这样的事情

function randomGen($min, $max, $quantity,$rangestep) {
    $numbers = range($min, $max,$rangestep);

    $tmp = array_slice($numbers, 0, $quantity);
    sort($tmp);
    shuffle($tmp);
    return $tmp;
}
echo '<pre>';
$arr = randomGen(2,7,5,1);
$count = 0;
$first = $arr[0];
$i = 1;
//for($i = 1; $i < count($arr); $i++) {
$counter = 0;
while ($i < count($arr)) {
  $ele = $arr[$i];
  if ($counter >=3) {
    $counter = 0;
    $arr = randomGen(2,7,8,2);
    $first = $arr[0];
    $i = 1;
  }
   else {
   if ($ele - $first === 1) {
      $counter++;

      //continue;
   }
  $first = $ele;
  }
 $i++;
 } 
  print_r($arr);
 die;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM