简体   繁体   English

如何构建不同元素的随机 integer 数组?

[英]How to build a random integer array of distinct elements?

I am trying to create a method that fills an array with random integers with no duplicate elements.我正在尝试创建一种方法,该方法用没有重复元素的随机整数填充数组。 I'm having trouble making sure each element that is put into the new array is distinct.我无法确保放入新数组的每个元素都是不同的。

Ex.前任。 if numOfDigits is 5, then I'd like something like [3][8][2][6][1].如果 numOfDigits 是 5,那么我想要 [3][8][2][6][1] 之类的东西。 At the moment it either outputs something like [9][0][1][0][0] or infinitely loops.目前,它要么输出类似 [9][0][1][0][0] 的内容,要么输出无限循环。

  private static int[] hiddenSet(int numOfDigits){
    int[] numArray = new int[numOfDigits];
    int temp;
    for (int i = 0; i < numArray.length;  i++){
      do {
        temp = getRandomNum(10);
        numArray[i] = temp;
      } while (isDigitNew(numArray, temp));
      //Each random num must be unique to the array
    }
    return numArray;
  }

  private static boolean isDigitNew(int[] numArray, int index){
    for (int i = 0; i < numArray.length; i++) {
      if (numArray[i] == index) {
        return false;
      }
    }
    return true;
  }

One easy approach is to fill the array with distinct digits then shuffle it.一种简单的方法是用不同的数字填充数组,然后打乱它。

public static int[] getRandomDistinct(int length) {
    Random rand = new Random();
    int[] array = new int[length];

    // Fill with distinct digits
    for (int i = 0; i < length; i++) {
        array[i] = i;
    }

    // Swap every element with a random index
    for (int i = 0; i < length; i++) {
        int swapWith = rand.nextInt(length);

        int tmp = array[i];
        array[i] = array[swapWith];
        array[swapWith] = tmp;
    }

    return array;
}

Your algorithm takes quadratic time at best.您的算法最多需要二次时间。 When the choice of random numbers becomes less looping may take ages.当随机数的选择变得更少时,循环可能需要很长时间。 Even infinite might be possible.甚至无限可能也是可能的。

Add a positive random number + 1 to the previous generated number.将一个正随机数 + 1 添加到先前生成的数字。 The desired range of numbers needs a bit of care.所需的数字范围需要一点小心。

At he end shuffle.在他结束洗牌。 If you start with a List, you can use Collections.如果从 List 开始,则可以使用 Collections。 shuffle.洗牌。

You can use IntStream like this.您可以像这样使用IntStream

private static int[] hiddenSet(int numOfDigits) {
    return IntStream.iterate(getRandomNum(10), i -> getRandomNum(10))
        .distinct()
        .limit(numOfDigits)
        .toArray();
}

and

public static void main(String[] args) {
    int[] a = hiddenSet(5);
    System.out.println(Arrays.toString(a));
}

output: output:

[7, 4, 5, 0, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM