隨機生成給定範圍內N個不重複的數

public class Test2 {
	public static void main(String[] args) {
		int [] nums =Test2.randomCommon(1, 10, 5);
		for(int i:nums){
			System.out.println(i);
		}
		
	}
	/**
	 * 隨機指定範圍內N個不重複的數 最簡單最基本的方法
	 * 
	 * @param min
	 *            指定範圍最小值
	 * @param max
	 *            指定範圍最大值
	 * @param n
	 *            隨機數個數
	 */
	public static int[] randomCommon(int min, int max, int n) {
		if (n > (max - min + 1) || max < min) {
			return null;
		}
		int[] result = new int[n];
		int count = 0;
		while (count < n) {
			int num = (int) (Math.random() * (max - min)) + min;
			boolean flag = true;
			for (int j = 0; j < n; j++) {
				if (num == result[j]) {
					flag = false;
					break;
				}
			}
			if (flag) {
				result[count] = num;
				count++;
			}
		}
		return result;
	}
}

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