import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Number {
/**
*
* @param count 随机数的数目
* @param from 随机数的最小值
* @param to 随机数的最大值
* @return 返回count个,值介于from和to之间的不同随机数;
* 由于数据集的各个元素值不相同,所以count值必须小于或等于to-from+2
*/
public static Set<Integer> DifRandom(int count, int from, int to) {
Set<Integer> randoms = new HashSet<Integer>();
while (randoms.size() < count) {
int num = (int) (Math.random() * (to - from + 1)) + from;
randoms.add(num);
}
return randoms;
}
public static void main(String[] args) {
long time = new Date().getTime();
Set<Integer> nums = DifRandom(1000000, 10000, 10000000);
Iterator<Integer> it =nums.iterator();
while(it.hasNext()) {
System.out.println(it.next().intValue());
}
System.out.println("随机数数目: " + nums.size()+ ", 耗时:" + (new Date().getTime() - time) + "ms");
}
}
转载于:https://my.oschina.net/hasonger/blog/208527