/**
* 随机生成总数相等的一个数组
* @author xuxk
* @time 2016年5月17日 上午10:31:03
*/
public class RandSumQuery {
public static void main(String[] args) {
int count = 10;
int total=300;
int min=total/count-1;
System.out.println(min);
int[] result = new int[count];
result = getRandomAndTotalEq(count, total, min, result);
System.out.println(result);
int sum=0;
for (int i = 0; i < result.length; i++) {
System.out.println("--:"+i+":"+result[i]);
sum+=result[i];
}
System.out.println("总和:"+(sum));
}
/**
* 获取一个随机的总和相等的数组
* @param count
* @param total
* @param min
* @return
*/
public static int[] getRandomAndTotalEq(int count,int total,int min,int[] result){
int random = 0 ;
if(count>1){
int useTotal = total-(count-1)*min;
random =(int)(Math.random()*(useTotal-1)+1);
}else{
random = total;
}
result[count-1] = random;
int surplusTotal = total-random;
count--;
if(count>0){
getRandomAndTotalEq(count,surplusTotal,min,result);
}
return result;
}
}
转载于:https://blog.51cto.com/lailai/1774315