Home > front end >  How to build a random integer array of distinct elements?
How to build a random integer array of distinct elements?

Time:11-28

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]. At the moment it either outputs something like [9][0][1][0][0] or infinitely loops.

  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;
  }

CodePudding user response:

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 - 1; i  ) {
        int swapWith = i   rand.nextInt(length - i);

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

    return array;
}

CodePudding user response:

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. The desired range of numbers needs a bit of care.

At he end shuffle. If you start with a List, you can use Collections. shuffle.

CodePudding user response:

You can use IntStream like this.

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:

[7, 4, 5, 0, 1]
  • Related