【问题标题】:How to generate a random number with fixed length only with 0's and 1's and a fixed amount of 1's?如何生成只有0和1以及固定数量的1的固定长度的随机数?
【发布时间】:2015-05-23 10:18:45
【问题描述】:

我做了一些研究,但没有为我的问题找到任何解决方案。

我要归档的内容:

从 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。

如何修复此代码?还是有更简单的方法?

【问题讨论】:

  • 我想你得把你的问题说得够清楚,这样大家才能理解和帮助你。

标签: php loops random while-loop numbers


【解决方案1】:

这应该适合你:

不需要循环。只需首先用 1 的 $many 次填充数组。然后 array_merge() 数组中的 0 填充到 $length 元素。

最后只需shuffle() 数组和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

【讨论】:

  • 请解释一下downVote,以便我改进这个答案。
  • @FrancisAlvin 我没有问题。这应该是对 OP 问题的回答
  • 啊哈..是的。你有一个有趣的解决方案。 :) @Rizier123 很抱歉,我是写给 Welly 的。
  • 优秀..正是我要找的...非常感谢
  • 对不起.. 还有什么问题.. 我怎样才能在 011010 之间分开,所以我可以把它放在表中,比如第 1 列是 0,第 2 列是 1 等等
猜你喜欢
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 2012-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-16
  • 1970-01-01
相关资源
最近更新 更多