Generate mathematical combinations with array in PHP

Generate all possible combinations of 15 elements from an array with 17 items. This is a hypothetical situation. It should suit any combination n by p.

Total of 136 combinations. Using the mathematical formula for combinations:

Cn,p
C17,15 = 17!/(15!*2!)

???? how to do? suggestions, examples?

//Código

//array com 17 dezenas

dezenas = ["2", "4", "5", "6", "7", "9", "10", "12", "15", "16", "18", "20", "21", "22", "23", "24", "25"];

//Gerar todas combinações possíveis de array com 15 dezenas

 array1 = ["2", "4", "5", "6", "7", "9", "10", "12", "15", "16", "18", "20", "21", "22", "23"];

 array2 = ["2", "4", "5", "6", "7", "9", "10", "12", "15", "16", "18", "20", "21", "22", "24"];

//etc... etc...
Author: Inkeliz, 2017-08-01

1 answers

Combinations of 17 elements from 15 to 15 can be defined recursively using the following function:

$dezenas = array("2", "4", "5", "6", "7", "9", "10", "12", "15", "16", "18", "20", "21", "22", "23", "24", "25");

function combinacoesDe($k, $xs){
     if ($k === 0)
         return array(array());
     if (count($xs) === 0)
         return array();
     $x = $xs[0];
     $xs1 = array_slice($xs,1,count($xs)-1);
     $res1 = combinacoesDe($k-1,$xs1);
     for ($i = 0; $i < count($res1); $i++) {
         array_splice($res1[$i], 0, 0, $x);
     }
     $res2 = combinacoesDe($k,$xs1);
     return array_merge($res1, $res2);
}


print_r(combinacoesDe(15,$dezenas));

Result-ideone

Starting with PHP 5.4 you can also use the collapsed array syntax, which exchanges array() for [].

Link to generate combination online online calculator: Combinatorics. Generator of combinations



The number of combinations is given by Formula

                 n!
      Cn,p = ___________     
             p! (n – p)!
  • n is the number of elements in a set
  • p is a natural number less than or equal to n, which represents the number of elements that will form the groupings.

Doing the account without calculating machine we will have:)

                 17!
     C17,15 = ____________     
             15! (17 – 15)!


               (1*2*3*.......*15)*16*17     16*17
     C17,15 =  _________________________ = ______ = 8*17= 8*(10+7)=80+56=136
               (1*2*3*.......*15)*1*2        1*2
 2
Author: Leo Caracciolo, 2020-06-18 17:53:28