I have a function that takes randomly take 4 unique numbers from an array and multiply them. Problem with the script below is it only print out the products. I would like for each set of 4 numbers and its product to be in its own array and all the arrays into a main array, forming a 2 dimensional array.
My current script:
//Pruning outcome from controlled lists of Prime Numbers
$primes = array(2, 3, 5, 7, 11, 13, 17, 19, 23);
function getAllCombinations($arr, $n, $selected = array(), $startIndex = 0) {
if ($n == 0) {
$product = 1;
foreach ($selected as $prime) {
$pr[] = $prime;
$product *= $prime;
$pr[] = $prime;
}
echo "Product: $productn";
return;
}
for ($i = $startIndex; $i < count($arr); $i++) {
$selected[] = $arr[$i];
getAllCombinations($arr, $n - 1, $selected, $i + 1);
array_pop($selected); // Backtrack and remove the element for next iteration
}
}
getAllCombinations($primes, 4);
Instead of using echo resulting as :
Product: 210 Product: 330 Product: 390 Product: 510,
I would prefer them to be in 2 dimensional array so that each row is the combination of numbers with the product as the last element in the row:
array (
0 =>
array (
0 => 2,
1 => 3,
2 => 5,
3 => 7,
4 => 210,
),
1 =>
array (
0 => 2,
1 => 3,
2 => 5,
3 => 11,
4 => 330,
),
2 =>
array (
0 => 2,
1 => 3,
2 => 5,
3 => 13,
4 => 390,
),
...
)
2
Answers
I believe this may be what you are trying to do.
PHP:
OUTPUT:
I prefer the elegance of not defining a reference variable to collect all of the results. Instead, I’ve refactored your script to return the result array.
I’ve used
...
(spread operator) to allow the accumulation of payloads without deviating from the desired 2d structure.Code: (Demo)