一个简单的算法_应该是最笨的写法了

本文介绍了一个使用PHP编写的算法,该算法根据特定条件将数值分配到预设的模板数组中。通过递归减法的方式实现了数值的有效拆分,并考虑了边界情况。此算法可以应用于资源分配或任务调度等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php

header("Content-type: text/html; charset=utf-8");
$count = 19;//5 9另外处理 


$tempArray = array(2,3,4);
$_template = array();

if($count >= 2){
	if(in_array($count, $tempArray)){
	    array_push($_template, $count);
	}else{
		if($count == 5){
		    array_push($_template, 2);
		    array_push($_template, 3);
		}else if($count == 9){
		    array_push($_template, 4);
		    array_push($_template, 2);
		    array_push($_template, 3);
		}else{
			Calculate($_template, $count, $tempArray);
		}	
	}
}else{ 
     array_push($_template, $count);
}

function Calculate(&$_template, $count, $tempArray)
{
	 shuffle($tempArray);
     while($count>=2)
     {
          $templateid = array_rand($tempArray,1);
          $templateValue = $tempArray[$templateid];
          #echo "模板值为:{$templateValue}<BR><BR>";

          if($count >= 2){
          	 if($count >= $templateValue){
		          $count = $count - $templateValue;
		          #echo "count:{$count}<BR><BR>"; 
		          array_push($_template, $templateValue);
		          //echo $templateid."<BR><BR>";          	 	
          	 }else{
                  array_push($_template, $count);
                  $count = 0;
          	 }
          }
     }

     if($count == 1){
     	$isZero = false;
        #echo "最后还有一个哦{$count}<BR><BR>";
        if(count($_template) >= 1){
             foreach($_template as $key=>$val){
                 if($val <= 3 ){
                 	 #echo "最后一个处理完成";
                 	 $_template[$key] = $val+1;
                 	 $isZero = true;
                 	 break;
                 }
             }
        }
        if($isZero == false){
        	#echo "<h1>只能添加一个模板了</h1>";
        	array_push($_template, $count);
        }
     }
}

echo "<BR><BR><BR>最后取得的模板数组为:<BR><BR>";
var_dump($_template);


?>

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值