阅读背景:

RandomUtil随机数工具类

来源:互联网 

package com.imooc.test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomUtil {

	/** 
	  * 在必定规模内生成给定数目标不反复随机数, 如果开端到停止的数目少于num的数目会抛出数组越界的毛病, 
	  * 如果相等则会返回一个排好序的数组,即从begin到end 否则返回随机数组(list),不反复,不排序 
	  * 
	  * @author Cesar 
	  * @param begin 
	  *            开端值 
	  * @param end 
	  *            停止值 
	  * @param num 
	  *            请求数目 
	  * @return 
	  */ 
	 public static List<Integer> getRandomNum(int begin, int end, int num) { 
	  int size = end-begin+1; 
	  int[] all = new int[size]; 
	  Random random = new Random(); 
	  List<Integer> result = new ArrayList<Integer>(); 
	  int x; 
	  if (size < num) { 
	   throw new ArrayIndexOutOfBoundsException("数组越界"); 
	  } else if (size == num ) { 
	   for (int i = 0; i < num; i++) { 
	    result.add(begin++); 
	   } 
	  } else { 
	   for(int i=0;i<size;i++){ 
	    all[i] = begin++; 
	   } 
	   for(int i = 0;i<num;i++){ 
	    x = random.nextInt(size);//取得坐标 
	    result.add(all[x]); 
	    all[x] = all[size-1];
	    size--; 
	   } 
	  } 
	  return result; 
	 } 
	 
	 public static void main(String[] args) {
		 System.out.print( getRandomNum(100, 200, 20));
		
	}
}
package com.imooc.test;

import java.util.ArrayLi




你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: