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.
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. I am trying to modify the above code so that it does not return more than 3 consecutive numbers. 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.
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.
Aucun commentaire:
Enregistrer un commentaire