You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改PHP组合函数,生成含4数组合与乘积的二维数组

修改PHP组合函数生成包含数字与乘积的二维数组

现有一段PHP代码,功能是从质数数组中选取4个唯一数字并计算乘积,但当前函数仅输出乘积结果。需要修改代码,生成一个二维数组,其中每个子数组包含一组选中的4个数字,并将乘积作为该子数组的最后一个元素。

当前代码

//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);

当前输出

Product: 210 Product: 330 Product: 390 Product: 510, 

期望输出格式

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,
  ),
  ...
)

修改后的代码

//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) {
    $result = [];
    if ($n == 0) {
        // 计算选中数字的乘积
        $product = array_product($selected);
        // 组装包含数字和乘积的子数组
        $combination = $selected;
        $combination[] = $product;
        return [$combination];
    }

    for ($i = $startIndex; $i < count($arr); $i++) {
        $selected[] = $arr[$i];
        // 递归获取子组合并合并到结果数组
        $result = array_merge($result, getAllCombinations($arr, $n - 1, $selected, $i + 1));
        array_pop($selected); // 回溯移除当前元素,准备下一轮循环
    }

    return $result;
}  

// 获取最终的二维数组结果
$combinations = getAllCombinations($primes, 4);
// 打印结果
print_r($combinations);

关键修改说明

  • 调整函数逻辑,让其返回数组而非直接输出:递归过程中收集所有符合条件的组合,最终返回完整的二维数组
  • 使用array_product()简化乘积计算,也可以保留原手动循环的方式,效果一致
  • 当选中4个数字时,复制选中数组并追加乘积,将这个子数组作为当前递归层级的结果返回
  • 递归调用时合并子函数返回的结果集,最终汇总所有组合

内容的提问来源于stack exchange,提问作者Joe Shamuraq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 01:55:04