隨機產生 指定的個數和指定的總和的數字

/**
 * 隨機生成總數相等的一個數組
 * @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;
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章