开发者

Function to output probability in PHP

I'm trying to find a function that takes a number and outputs the expected results as follows:

if input=1 then output should be Array{'0','1'}

if input=2 then output should be Array{'00','01','10','11'}

if input=3 then output should be Array{'000','001','010','011','100','101','110','111'}

and so on.It's similar to flipping a number of coins.

I don't kno开发者_运维知识库w if there is a function in php that does that, but if there isn't could anyone please show me how it's done?


In fact that are just the numbers from 0 to 2^{input}-1 in binary notation

$max = pow(2, $input);
$result = array();
for ($i = 0; $i < $max; $i++) {
  $result[] = str_pad(base_convert($i, 10, 2), $input, 0, STR_PAD_LEFT);
}


Same as @KingCrunch answer, but more concise:

foreach (range(0, pow(2, $input)) as $i)
{
    $result[] = sprintf('%0' . $input . 'b', $i);
}

Or, if you don't like sprintf:

foreach (range(0, pow(2, $input)) as $i)
{
    $result[] = str_pad(decbin($i), $input, 0, STR_PAD_LEFT);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜