Generating random array of fixed length (Java)

前端 未结 3 1527
南方客
南方客 2021-01-27 00:07

im just looking to change my code so that a random array of a fixed length of 100 integers is generated every time the code is ran rather than just have a pre-set array within t

3条回答
  •  情话喂你
    2021-01-27 00:45

    The below would fill an array of 100 integers with Random numbers from 1-1000

    int[] numbers= new int[100];
    Random rand = new Random();
    for (int i = 0; i < numbers.length; i++) {
          numbers[i] = rand.nextInt(1000);
    }
    

    However note that the above code might insert duplicates. If you want to avoid that, using a List in parallel to the array and checking whether the generated value already exists should ensure uniqueness :

    int[] numbers= new int[100];
    List numbersList = new ArrayList(numbers.length);
    Random rand = new Random();
    for (int i = 0; i < numbers.length; i++) {
        int j = rand.nextInt(1000);
        while (numbersList.contains(j)) {
            j = rand.nextInt(1000);
        }
        numbers[i] = j;
        numbersList.add(j);
    }
    

    Even though I think it would be wiser to get rid of the array and use just the List...

提交回复
热议问题