-1
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Test {

        private static int[] readArray(int arraySize) {
            Random r = new Random();
            int[] arr = new int[arraySize];

            for (int i=0; i<arr.length; i++) {
                arr[i] = r.nextInt(arraySize);
            }
            return arr;
        }

        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter array size: ");
            int size = sc.nextInt();
            int[] arr = readArray(size);
            System.out.println(Arrays.toString(arr));
        }
}

How to modify above code, so that if I input 100, I have an array of 100 numbers without duplicates ?

Thank you.

3 Answers3

0

Use a while loop, to add numbers in a Set (no duplicate) until you reach the good size

private static Integer[] readArray(int arraySize) {
    Set<Integer> unique = new LinkedHashSet<>();
    Random r = new Random();
    while (unique.size() != arraySize)
        unique.add(r.nextInt(arraySize));
    return unique.toArray(new Integer[0]);
}
azro
  • 53,056
  • 7
  • 34
  • 70
0

Use Set to keep track of elements present in the array till now and make use of it to avoid duplicates

private static int[] readArray(int arraySize) {
    Set<Integer> set = new HashSet<>();
    Random r = new Random();
    int[] arr = new int[arraySize];
    int random;
    for (int i=0; i<arr.length; i++) {
        while (set.contains(random = r.nextInt(arraySize)));
        arr[i] = random;
        set.add(random);
    }
    return arr;
}
Turtle
  • 667
  • 1
  • 6
  • 18
0

Question is duplicated: Creating random numbers with no duplicates

Change this:

for (int i=0; i<arr.length; i++) {
    arr[i] = r.nextInt(arraySize);
}

to this:

arr = r.ints(0, arraySize).distinct().limit(arraySize).toArray();

or

arr = r.ints(0, 10000).distinct().limit(arraySize).toArray();

10000 is upper limit.

Wing Kui Tsoi
  • 474
  • 1
  • 6
  • 16