I have a function which gives me all combination of values, in an array with fixed length a fixed sum :
// $n_valeurs is the length of the array
// $x_entrees is the sum
function distributions_possibles($n_valeurs, $x_entrees, $combi_presences = array()) {
if ($n_valeurs == 1) {
$combi_presences[] = $x_entrees;
return array($combi_presences);
}
$combinaisons = array();
// on fait appel à une fonction récursive pour générer les distributions
for ($tiroir = 0; $tiroir <= $x_entrees; $tiroir++) {
$combinaisons = array_merge($combinaisons, distributions_possibles(
$n_valeurs - 1,
$x_entrees - $tiroir,
array_merge($combi_presences, array($tiroir))));
}
return $combinaisons;
}
distributions_possibles(4,2);
// output :
[0,0,0,2]
[0,0,1,1]
[0,0,2,0]
[0,1,0,1]
[0,1,1,0]
[0,2,0,0]
[1,0,0,1]
[1,0,1,0]
[1,1,0,0]
[2,0,0,0]
I need to generate all possible combinations adding another parameter : a reference array $ref whose values are considered as limits.
All combination $combi generated must respect the rule : $combi[x] <= $ref[x]
For example with [2,1,1,0] we can't have [0,0,2,0], [0,2,0,0].
I created the following function to add the new parameter :
// $distribution is the array reference
// $similitude is the sum of values
function SETpossibilites1distri($distribution, $similitude){
$possibilites = [];
$all_distri = distributions_possibles(count($distribution), $similitude);
foreach($all_distri as $distri){
$verif = true;
$distri_possi = [];
for($x = 0; $x < count($distri); $x++){
if($distri[$x] > $distribution[$x]){
$verif = false;
break;
}
if($distribution[$x] == 0){
$distri_possi[$x] = null;
}
elseif($distribution[$x] > $distri[$x] && $distri[$x] != 0){
// si c'est une valeur fixée qui informe sur la distri_cach
if($this->distri_cach[$x] == $distri[$x]){
$distri_possi[$x] = $distri[$x]+.1;
}
else{
$distri_possi[$x] = $distri[$x]+.2;
}
}
else{
$distri_possi[$x] = $distri[$x];
}
}
if($verif){
$possibilites[] = $distri_possi;
}
}
return $possibilites;
}
This function makes me generate and filter a big list of combinations with the new parameter. I need to have a function which generates only the combinations I want. Do you have ideas ?