Search code examples
phpfunctionprobabilitycoin-flipping

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 know if there is a function in php that does that, but if there isn't could anyone please show me how it's done?


Solution

  • 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);
    }