2 independent events 3 times - enumerate the possible outcomes

不问归期 提交于 2019-12-24 10:42:56

问题


I looked around but I couldn't find anything that suited for this.

$n = 3;//number of events
$k = array(0,1);//possible outcomes

I'd like to have an array containing all the possible outcomes:

$result = array([0] => array(0,0,0), [1] => array(1,0,0)... [7] =>array(1,1,1));

I tried this long and static method that leads me to nothing useful:

for($a=0;$a<count($k);$a++) {
for($b=0;$b<count($k);$b++) {
for($c=0;$c<count($k);$c++) {
$push = array($a,$b,$c);
array_push($result,$push);
}}}

How can I re-write this to get a function that takes the n value into account? So if I change the value of $n to 4 I get an array like:

$result = array([0] => array(0,0,0,0), [1] => array(1,0,0,0)... [15] =>array(1,1,1,1));

回答1:


The key here is a recursive call.

<?php

function gen($n, $k) {
        if ($n == 1) {
                // Base case
                $out = array();
                foreach ($k as $elem) {
                        array_push($out, array($elem));
                }
                return $out;
        }

        $out = array();
        foreach ($k as $elem) {
                // Recursive call
                $prev = gen($n - 1, $k);

                foreach ($prev as $rec) {
                        array_push($rec, $elem);
                        array_push($out, $rec);
                }
        }
        return $out;
}       

print_r(gen(4, array(0,1)));

?>

This will build up the array one layer at a time for each recursive call.




回答2:


Is this what you want?

$n = 3;
$arr = array();
for ($i=0; $i<pow(2,$n); $i++) {
    $s = str_pad(decbin($i), 3, "0", STR_PAD_LEFT); 
    $a = array_reverse(preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY));
    $arr[] = $a;
}
print_r($arr);


来源:https://stackoverflow.com/questions/8506677/2-independent-events-3-times-enumerate-the-possible-outcomes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!