我试图从一组数字中得到非重复的随机数。每次我尝试从该数组中获取随机值时,它应该给我非重复随机数。不应重复先前的随机值
int[] integer_array = {0,1,2,3,4,5,6,7};
int random_no = should be random number from above array
int random_no2 = should be random number from above array other than random_no
int random_no3 = should be random number from above array other than random_no
and random_no2
可以为integer_array.length次生成数组的随机数。
答案 0 :(得分:0)
这是我的代码:
public static int[] getIndices(int maxValue, int numberOfIndices) {
// The result array.
int[] res = new int[numberOfIndices];
Random rng = new Random();
// A set of already used numbers.
TreeSet<Integer> was = new TreeSet<>();
for (int i = 0; i < numberOfIndices; i++) {
// Generate a new number in range [0..maxValue - i].
// It is a position of a new index in an array of unused values.
int cur = rng.nextInt(maxValue - i);
// Compute its position taking into account all values(used and unused)
// to obtain the real index.
for (int prev : was)
if (cur >= prev)
cur++;
// Add this index to the result array.
was.add(cur);
res[i] = cur;
}
return res;
}
它背后的想法是在未使用的值数组中生成一个新数字的位置(此数组未明确维护),然后计算实际索引值,同时考虑已使用的数字。
这种方法有什么好处,它只调用nextInt
numberOfIndices
次,并且无论nextInt
返回什么,都可以保证生成不同的数字。
答案 1 :(得分:0)
int[] integer_array = {0, 1, 2, 3, 4, 5, 6, 7};
Random r = new Random();
int random_no = r.nextInt(integer_array.length);
System.out.println(random_no);
int random_no2;
do {
random_no2 = r.nextInt(integer_array.length);
} while (random_no2 == random_no);
System.out.println(random_no2);
int random_no3;
do {
random_no3 = r.nextInt(integer_array.length);
} while (random_no3 == random_no || random_no3 == random_no2);
System.out.println(random_no3);