如何获得独特的随机int?

Jak*_*ała 0 java random android unique

static int n = -1;  
private static int repeatBuffer[] = new int[10];
static {
    repeatBuffer[0] = 0;
    //and more
    repeatBuffer[9] = 9;
}
static public void randomize() {

    do {
        Random r = new Random();
        randomNumber = r.nextInt(20);
    } while (!uniqueInt(randomNumber));
    Log.e(TAG, "" + randomNumber); //here I need have a unique int
}

private static Boolean uniqueInt(int random) {

    for (int i = 0; i < 9; i++) {
        if (random == repeatBuffer[i]) {
            return false;
        }
    }
    if (++n > 9)
        n = 0;
    repeatBuffer[n] = random;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

有时我两次得到相同的int,我想知道问题出在哪里?它甚至可以工作吗?我花了很多时间在这上面,我放弃了.我想我需要在代码中进行一些小调整:)

Sim*_*erg 5

获取随机int的一种更简单的方法是创建一个整数列表List<Integer>,并为其添加您想要的数字.然后使用随机洗牌Collections.shuffle(list);.现在从列表的开头开始阅读,每次都会得到一个唯一的随机int.

只需确保每次"读取"列表中的数字时,将其从列表中删除或增加您阅读的位置的索引.