如题,因为方法中刚好用到了递归,递归中有个知识点忘了,看了老半天所以记录下来。
方法一:递归的方法直接取得随机一组值
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);