Chester
Chester

Reputation: 13

Why does my output of randomly selected numbers contain duplicates?

My code needs to randomly select 6 numbers from a list ranging from 1 to 45.

Once when I ran my code (below) the output was [4, 4, 17, 18, 27, 37]. I was not expecting any duplicates in the output. How is it possible that there are duplicates? My code should be removing numbers from list as they are selected.

    Random rng = new Random(); 
    int size = 45;
    int sixList[] = new int[6];
    ArrayList<Integer> list = new ArrayList<Integer>(size);
    ArrayList<Integer> list2 = new ArrayList<Integer>(6);
    for(int i = 1; i <= size; i++) {
        list.add(i);
    }
    Random rand = new Random();
    for(int i = 0; list.size() > 39; i++){
        int index = rand.nextInt(list.size());
        if (index == 0){
            index = rand.nextInt(list.size());
            list2.add(index);
            list.remove(index);
        }else{
            list2.add(index);
            list.remove(index);
        }
    }
    Collections.sort(list2);
    System.out.print(list2);

Upvotes: 1

Views: 96

Answers (2)

Aaron Kurtzhals
Aaron Kurtzhals

Reputation: 2036

The problem is that you are adding the index value to your list of random numbers.

Change your code

list2.add(index);
list.remove(index);

To

list2.add(list.remove(index));

Upvotes: 1

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

List maintain index and does not care about duplicate elements at all. To avoid duplicates you must use Set rather than List. If you have any user-defined class going in the Set, then dont forget to implement equals() and hashcode() which are used to determine if elements are duplicate or not by the Set classes like HashSet.

If you have primitives going in you Set, then forget about duplicates as duplicates will be automatically handled for primitive data-types like int,long etc. So I suggest you to use Set rather than List. to avoid duplicate elements in the collection

Upvotes: 0

Related Questions