码迷,mamicode.com
首页 > 其他好文 > 详细

随机产生 指定的个数和指定的总和的数字

时间:2016-05-17 20:02:55      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:随机数

/**
 * 随机生成总数相等的一个数组
 * @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;
	}

}


本文出自 “东方小阁” 博客,请务必保留此出处http://lailai.blog.51cto.com/3362373/1774315

随机产生 指定的个数和指定的总和的数字

标签:随机数

原文地址:http://lailai.blog.51cto.com/3362373/1774315

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!