最近有一个需求,比较简单,就是如标题所说的,从N个元素中随机取m个元素,固然这m个元素是不能存在重复的。本觉得这么简单的需求,应该有现成的工具类来实现,可是几回查找竟然没找到(有知道的能够推荐下哈^_^)。只好本身实现了下。java
本身的实现思路也不知道是否是有问题,或者还有没有更好的思路来实现,因此在这里贴出来,供有兴趣的猿友提提建议、找找问题,或者找到更好的实现思路。dom
废话很少说,直接上代码(java实现)工具
/** * 随机取num个从0到maxVal的整数。包括零,不包括maxValue * @param num * @param maxValue * @return */ public static List<Integer> random(int num,int maxValue){ if(num>maxValue ){ num=maxValue; } if(num<0 || maxValue<0){ throw new RuntimeException("num or maxValue must be greater than zero"); } List<Integer> result = new ArrayList<Integer>(num); int[] tmpArray = new int[maxValue]; for(int i=0;i<maxValue;i++){ tmpArray[i]=i; } Random random = new Random(); for(int i=0;i<num;i++){ int index = random.nextInt(maxValue-i); int tmpValue = tmpArray[index]; result.add(tmpValue); int lastIndex = maxValue-i-1; if(index==lastIndex){ continue; }else{ tmpArray[index]=tmpArray[lastIndex]; } } return result; }