從N個元素的集合中隨機取m個元素的演算法實現

來源:互聯網
上載者:User

標籤:run   java   add   元素   ati   tin   int   runtime   ret   

最近有一個需求,比較簡單,就是如標題所說的,從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;    }

從N個元素的集合中隨機取m個元素的演算法實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.