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 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面