dongyi9298 2017-11-01 06:46
浏览 77
已采纳

在php中为另一个数组分配等于或小于0的目标数

Candidate array= {10, 1, 2, 7, 6, 1, 5};

Target Number = 15

Can distribute random target number=15 into candidate array?

Possible output of could be:

Assign equal or less with zero target number against candidate array like is:

 $output =array([10] => [2],[1]=>[0], [2]=>[2], [7]=>[5], [6]=>[3],  [1]=>[1], [5]=>[2]);
  • 写回答

1条回答 默认 最新

  • dongzhuoxie1244 2017-11-01 11:54
    关注

    Try the following, This will extract a random no between 1 & cardiate_array[$i]. After that it will reduce the target distribution number by that random number. Will continue until targetNumber is fully consumed.

    $candidate_array = array(10, 1, 2, 7, 6, 0, 5);
    $i = 0;
    
    $newArray = [] ;
    $number = 15; 
    
    //Precaution
    $sum = array_sum($candidate_array) ;
    if( $number > $sum ) {
        //we can only distribute only $sum amount maximum.
        $number = $sum ; 
    }
    
    //repeat until fully consumed.
    while( $number > 0 ) {
        foreach( $candidate_array as $i => $val ) {
            if( ! isset($newArray[$i]) ) {
                $newArray[$i] = 0 ;
            }
            if( $number > 0 ) {
                if( $val > 0 ) {
                    if( $newArray[$i] < $candidate_array[$i] ) {
                        //Find the maximum can be applied 
                        $max = $candidate_array[$i] - $newArray[$i] ;
                        //Second iteration ? limit max value. This can be improved more.
                        if( $max > $number ) {
                            $max = $number ;
                        }
                        $rnd = rand(1,$max ) ;
                        //EDIT: A rand results in integer value, which again check with max (float) value. There is possibility of extra 0.5 added in result array which will be solved here.
                        if( $rnd > $max ) {
                            $rnd = $max ;
                        }
                        $newArray[$i] += $rnd ;
                        //Consume the number assigned.
                        $number -= $rnd ;
                        continue;
                    }
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?