从N个元素的集合中随机取m个元素的算法实现

最近有一个需求,比较简单,就是如标题所说的,从N个元素中随机取m个元素,当然这m个元素是不能存在重复的。本以为这么简单的需求,应该有现成的工具类来实现,但是几次查找居然没找到(有知道的可以推荐下哈^_^)。只好自己实现了下。

  自己的实现思路也不知道是不是有问题,或者还有没有更好的思路来实现,所以在这里贴出来,供有兴趣的猿友提提建议、找找问题,或者找到更好的实现思路。

  废话不多说,直接上代码(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;
    }
posted @ 2017-04-04 19:06  张柯宇  阅读(1332)  评论(0编辑  收藏  举报
友情链接:回力鞋专卖店 | 中老年服装 | 新航道 | 雅思培训机构 | 雅思培训强化班