從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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM