生成n个随机数,要求n个数的和等于100
// 生成n个随机数,要求n个数的和等于100 function lessANumber(n, v) { var i, s = 0, r = [], x = v; for (i = 1; i < n; i++) { x = Math.random() * x; r.push(x.toFixed(0)); s += x; x = v - s; } r.push(x.toFixed(0)); return r; }
function random(Min,Max){ var Range = Max - Min; var Rand = Math.random(); return(Min + Math.round(Rand * Range)); } function randnum(n,max){ var arr = []; if(max > 0){ for(var i = 0;i<n;i++){ var num = 0; if(i == (n-1)){ num = max; }else{ if(max <= 0){ num = max = 0; }else{ num = random(0,max); max -= num; } } arr.push(num); } } return arr; }
function foo($n ,$max = 100){ $array = $zero = $normal = []; for($i=1;$i<=$n;$i++){ $array[] = mt_rand(0,100); } $k = $max / array_sum($array); //求出放大系数k foreach($array as $key => $val){ $value = floor($val * $k); //直接保留整数,以保证下一步的和肯定<100 if($value<1){ $zero[] = $value; }else{ $normal[] = $value; } } $sum = array_sum($normal); $diff = $max - $sum; //这个值肯定<100 if(!empty($zero)){ //如果有为0的值 $count = count($zero); foreach($zero as $z){ $normal[] = $diff / $count; } }else{ //随机分配给一个人 $key = array_rand($normal); $normal[$key] = $normal[$key]+$diff; } unset($array,$zero,$sum,$diff); return $normal; }
javascript里的Math.random() 函数, 在php里
function random($min = 0, $max = 1) { return $min + mt_rand()/mt_getrandmax()*($max-$min); }
php资料