我正在try 创建一个可能的组合列表,用于将质数数组中的4个随机 Select 的数字相乘,但无济于事.有什么建议吗?
这是一种相当直接的方法,我觉得我无意中错过了一些东西. 以下是我所听到的:
//Pruning outcome from controlled lists of Prime Numbers
$primes = array(2, 3, 5, 7, 11, 13, 17, 19, 21);
function getUniqueRandomProductsWithNumbers($arr, $n) {
$seen = array(); // Store seen combinations to avoid duplicates
$productsWithNumbers = array();
while (count($productsWithNumbers) < pow(count($arr), $n)) {
$selected = array_rand($arr, $n); // Get random indexes
sort($selected); // Sort to ensure order for checking duplicates
$key = implode(",", $selected); // Create a unique key based on sorted indexes
if (!isset($seen[$key])) {
$product = 1;
$numbers = array();
foreach ($selected as $i) {
$product *= $arr[$i];
$numbers[] = $arr[$i];
}
$seen[$key] = true;
$productsWithNumbers[] = array($numbers, $product);
}
}
return $productsWithNumbers;
}
$uniqueProducts = getUniqueRandomProductsWithNumbers($primes, 4);
echo "Unique Products with Numbers:\n";
foreach ($uniqueProducts as $productSet) {
echo "Numbers: ";
print_r($productSet[0]); // Print the numbers array
echo ", Product: " . $productSet[1] . "\n";
}
真的很感谢你们的指点.提前感谢...