1. 程式人生 > >[Java]不重複隨機數生成簡易演算法

[Java]不重複隨機數生成簡易演算法

方法一

通過單個數組簡易實現不重複隨機數生成,先上原始碼。

/**
* 獲取隨機陣列
* @param 源陣列
 * @param size 目標陣列大小
 * @return 隨機陣列
 */
public static int[] getRandomRes(int[] source,int size){
    if (source == null && size > source.length) {
        return;
    }
    int[] result = new int[size];
    Random random = new Random();
    for (int i = 0; i < size; i++) {
        int randomIndex = random.nextInt(source.length - 1 - i);
        int randomRes = source[randomIndex];
        result[i] = randomRes;
        int temp = source[randomIndex];
        source[randomIndex] = source[source.length - 1 - i];
        source[source.length - 1 - i] = temp;
    }
    return result;
}

下面看圖解,數字為陣列的index。

第一次迴圈

黑色數字表示能隨機到的數,紅色代表不能隨機到數。
因此只能隨機到index:0~4的數,假設是2,然後將2與index5互換位置。

第一次迴圈結果

此時結果result[] = {2}

繼續迴圈

第二次迴圈

從前index:0~3中迴圈,假設取出index0,與index4互換

此時結果為result = {2,0}

依次類推。

優點:簡單快捷
缺點:每次無法取到最後一個數。

方法二

不斷隨機,使用Set去重

/**
*生成隨機陣列
*@param size 目標陣列大小
*@param max 目標數最大值
*/
public Set<Integer> getRandomSet(int size,int max){
    Random random= new Random();
    Set<Integer> result= new LinkedHashSet<Integer>();
    while (generated.size() < size)
    {
        Integer next = rng.nextInt(max) + 1;
        generated.add(next);
    }
}

此處使用LinkedHashSet保證插入順序與結果相同。