I have a function 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: $product\n";
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);
The output:
Product: 210 Product: 330 Product: 390 Product: 510, etc.
The preferred method is a 2 dimensional array as such:
[0][0] =>2 [0][1] =>3 [0][2]=>5 [0][3]=>7 and the product would be in [0][4] =>210
[1][0] =>2 [1][1] =>3 [1][2]=>5 [1][3]=>11 and the product would be in [1][4] =>330
etc.
Any pointers is greatly appreciated.