dragon0023 2012-04-04 02:08
浏览 26

为所有潜在组合创建动态for循环PHP函数

The code below will create an array for all possible combination that can occur when you have four different variables. The variables always need to equal 1. The for loops I have created work and I understand how to make this work for more variables, but can I make this dynamic? I need to have a function that has how many variables there are as a parameter. If there are three variables create the three forloops. If there are 10... create the 10 corresponding for loops to determine all possible combinations.

$anarray2 = array();
for( $a = 1; $a <= 97; $a++ ) {
  for( $b = 1; $a + $b <=98 ; $b++ ) {
    for( $c = 1; $a + $b + $c <= 99; $c++ ) {
      $d = 100 - ( $a + $b + $c );
      $var_1 = $a / 100;
      $var_2 = $b / 100;
      $var_3 = $c / 100;
      $var_4 = $d / 100;
      $anarray2[] = array( $var_1, $var_2, $var_3, $var_4 );
    }
  }
}
print_array( $anarray2 );
  • 写回答

1条回答 默认 最新

  • douwen9534 2012-06-06 11:44
    关注

    You're effectively looking to share out I identical items to N people in all of the different possible ways.

    If there is one person (N==1), then there is only one way to do this - give that person all I items.

    If there is more than one person (N>1), then we can consider how many items can be assigned to the first person, and then what the possible assignments are for the remaining N-1 people in each case.

    This leads to a nice recursive solution. Firstly we solve the problem for N=1:

    function assign($I, $N) {
        $anarray = array();
    
        if ($N == 1) {
            $anarray[] = array($I);
        } else {
            // Coming up...
        }
    
    return $anarray;
    }
    

    Now we solve the problem for N=k (some constant) in terms of N=k-1 - that is, we solve the problem using the solution to a smaller problem. This will reach all the way back to the solution when N=1.

    function assign($I, $N) {
        $anarray = array();
    
        if ($N == 1) {
            $anarray[] = array($I);
        } else {
            for ($i = $I; $i < $I; $i++) {
                foreach (assign($I - $i, $N - 1) as $subproblem) {
                    $anarray[] = array_merge(array($i), $subproblem);
                }
            }
        }
    
        return $anarray;
    }    
    

    Something like that should do the job.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集