Java 从数字数组中获取非重复随机数

Java 从数字数组中获取非重复随机数,java,math,random,Java,Math,Random,我试图从一组数字中得到不重复的随机数。每次我尝试从那个数组中获取随机值时,它都会给我一个不重复的随机数。之前的随机值不应重复 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

我试图从一组数字中得到不重复的随机数。每次我尝试从那个数组中获取随机值时,它都会给我一个不重复的随机数。之前的随机值不应重复

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
可以为整数数组生成数组中的随机no。长度时间。

以下是我的代码:

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;
}
publicstatic int[]getindex(int-maxValue,int-numberofindex){
//结果数组。
int[]res=新的int[numberofindex];
随机rng=新随机();
//一组已经使用过的数字。
TreeSet was=新TreeSet();
对于(int i=0;i=上一个)
cur++;
//将此索引添加到结果数组中。
was.add(cur);
res[i]=cur;
}
返回res;
}
其背后的思想是在未使用值数组中生成一个新数字的位置(该数组没有明确维护),然后计算实际索引值,同时考虑已使用的数字。

此方法的优点在于,它只调用
nextInt
numberofindexes
并保证生成不同的数字,而不管
nextInt
返回什么

您需要的不是随机数序列,而是数字1..n的无序排列,
Collections.shuffle()
方法将为您提供此功能。不,不是这样的。就像我得到一个随机数一样不,我不会再得到相同的随机数。它看起来适合长距离,但对于短距离,它会不断重复数字。你只是不想连续两次使用相同的值吗?更新了我的问题…这个问题不清楚。为什么不能直接使用Collections.shuffle()?洗牌集合后,您可以通过直接迭代以新的随机顺序读出它们。@hsuk我的代码返回索引,因此,如果数组中的所有元素都是不同的,它几乎可以满足您的需要。
    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);