已知a个$a,b个$b,c个$c相加要等于$total 求a,b,c的随机一组值

如题,因为方法中刚好用到了递归,递归中有个知识点忘了,看了老半天所以记录下来。

方法一:递归的方法直接取得随机一组值

function get_str($a,$b,$c,$total){
$arr = array();
$total_2 = $total;
$n = rand(0,floor($total_2/$a));//随机一个数
$total_2 = $total_2-$a*$n;
if($total_2 > 0){
$m = rand(0,floor($total_2/$b));//随机一个数
$total_2 = $total_2-$b*$m;
if($total_2 > 0){
if($total_2%$c > 0){
//有余数
$arr = get_str($a,$b,$c,$total); //一开始我只是写了get_str($a,$b,$c,$total); 函数若有走这一步,那么调用是不会有返回值得
return $arr; //注意:(作用域)递归函数返回的是它函数的东西,所以我们在最外层需要return递归函数的返回值

}else{
$arr = array($n,$m,$total_2/$c);
return $arr;
}
}else{
$arr = array('a'=>$n,'b'=>$m,'c'=>0);
return $arr;
}
}else{
$arr = array('a'=>$n,'b'=>0,'c'=>0);
return $arr;
}
}


$arr = get_str(2,3,4,100);
print_R($arr);


方法二:计算出所有的情况 再随机从里面取得一组数据

$a = 2;
$b = 3;
$c = 4;
$total = 100;
$n = ceil($total/$a);
for ($i = 0; $i <= $n; $i++) 

$total_2 = $total;
$total_2 = $total_2-$a*$i;
if($total_2 >= 0){
$m = ceil($total_2/$b);
for ($j = 0; $j <= $m; $j++){
$total_3 = $total_2;
$total_3 = $total_3-$b*$j;
if($total_3 >= 0){
if($total_3%$c > 0){
//有余数

}else{
$arr[] = array('a'=>$i,'b'=>$j,'c'=>($total_3/$c));
}
}
}
}



print_R($arr);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值