Java array fill unique random number

Description

Java array fill unique random number

import java.util.Arrays;
import java.util.Random;

public class Main {
  public static int[] uniqueRandom(int length) {
    Random rand = new Random();
    int[] nums = new int[length];
    //from  w w  w  .  j  a v a 2s.c  o  m
    boolean[] check = new boolean[length];
    
    for (int k = 0; k < length; k++) {
      int rnd = rand.nextInt(length);
      //check if the check array index has been set
      //if set regenerate 
      while (check[rnd]) {
        rnd = rand.nextInt(length);
      }
      nums[k] = rnd;
      check[rnd] = true;
    }
    return nums;
  } 
  public static void main(String args[]) {
    int length = 10;
    int[] a = uniqueRandom(length);
    System.out.println(Arrays.toString(a));

  }
}



PreviousNext

Related