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;
}
有时我会得到相同的 int 两次,我想知道问题出在哪里?这还有效吗?我在这上面花了很多时间,最后我放弃了。我想我需要对代码进行一些小调整:)
最佳答案
获取随机 int 的更简单方法是创建整数列表 List<Integer>
,添加您想要的数字。然后使用 Collections.shuffle(list);
重新排列列表。现在从列表的开头开始阅读,每次都会得到一个唯一的随机整数。
只需确保每次您从列表中“读取”一个数字时,要么将其从列表中删除,要么增加您读取位置的索引。
关于java - 如何获得唯一的随机整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18835964/