Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create an array of random elements without duplicates?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading