如何生成固定长度的随机数,只有 0 和 1 以及固定数量的 1?
How to generate a random number with fixed length only with 0's and 1's and a fixed amount of 1's?
我做了一些研究,但没有找到解决我的问题的方法。
我要归档的内容:
从 0 ($min
) 和 1 ($max
) 中生成一个随机数,但随机数中有固定数量 ($many
) 的 1。随机数的长度应为 6,如我的 while 循环 (while($xLoop <= 6)
).
这是我当前的代码:
$min = 0;
$max = 1;
$many = 3;
$xLoop = 1;
while($xLoop <= 6) {
$nRand = mt_rand($min,$max);
if($nRand == 1){ //if random number comes out number 1
$many--; // Prevent number 1 more then $many...
//Do something...
}else{ //if random number comes out not number 1
//Do something and still looping until get 6 times
}
echo $nRand.' - '.$many.'</br>'; //For debugin... i want to see how many number 1 comes out.
$xLoop++;
}
它会循环 6 次,所以我们有一个长度为 6 的随机数,但我希望我的随机数中有固定数量的 1,即 $many
(这里是 3)。其余的用 0 填充,直到我们达到长度 6。
如何修复此代码?或者有更简单的方法吗?
这应该适合你:
不需要循环。只需先用 1 的 $many
次填充一个数组。然后 array_merge()
包含 0 的数组,您将其填充到 $length
个元素。
最后shuffle()
the array and implode()
打印它
<?php
$min = 0;
$max = 1;
$many = 3;
$length = 6;
$arr = array_fill(0, $many, $min);
$arr = array_merge($arr, array_fill($many, $length-$many, $max));
shuffle($arr);
echo implode("", $arr);
?>
可能的输出:
011010
我做了一些研究,但没有找到解决我的问题的方法。
我要归档的内容:
从 0 ($min
) 和 1 ($max
) 中生成一个随机数,但随机数中有固定数量 ($many
) 的 1。随机数的长度应为 6,如我的 while 循环 (while($xLoop <= 6)
).
这是我当前的代码:
$min = 0;
$max = 1;
$many = 3;
$xLoop = 1;
while($xLoop <= 6) {
$nRand = mt_rand($min,$max);
if($nRand == 1){ //if random number comes out number 1
$many--; // Prevent number 1 more then $many...
//Do something...
}else{ //if random number comes out not number 1
//Do something and still looping until get 6 times
}
echo $nRand.' - '.$many.'</br>'; //For debugin... i want to see how many number 1 comes out.
$xLoop++;
}
它会循环 6 次,所以我们有一个长度为 6 的随机数,但我希望我的随机数中有固定数量的 1,即 $many
(这里是 3)。其余的用 0 填充,直到我们达到长度 6。
如何修复此代码?或者有更简单的方法吗?
这应该适合你:
不需要循环。只需先用 1 的 $many
次填充一个数组。然后 array_merge()
包含 0 的数组,您将其填充到 $length
个元素。
最后shuffle()
the array and implode()
打印它
<?php
$min = 0;
$max = 1;
$many = 3;
$length = 6;
$arr = array_fill(0, $many, $min);
$arr = array_merge($arr, array_fill($many, $length-$many, $max));
shuffle($arr);
echo implode("", $arr);
?>
可能的输出:
011010