Why does this program not stop duplicates in the array?

remove duplicates from array in java
remove duplicates from array c++
remove duplicates from unsorted array - java
remove duplicates from array in c#
remove duplicates from sorted array javascript
remove duplicates from array - leetcode
remove duplicates from array in python
java program to remove duplicates from string array

I'm trying to write a program that generates six random integers, and return them to the user without any of the numbers being duplicates. Why do duplicates still get through?

I've searched it up on Google and tried a few of the results, but none of them seemed to work. I thought of my own method to try to solve this issue, by doing the following:

Using a for loop, I store one number at a time from drawnNums (the array with six random numbers) in numToCheck. There is also a variable numOfDuplicates which stores how many of that number it found. Using another for loop, I go through all the numbers in drawnNums and compare it with numToCheck, and add one to numOfDuplicates. It obviously finds itself, so I have an if statement that only redraws numbers if numOfDuplicates is >= 2. This is in the same function where I create the array, so it should create a new array and check through again, redrawing until there are no duplicates.

In my mind, this should stop duplicates from being returned, but it doesn't.

This is from class I have created to generate the array, and what I described above.

// Private function to draw one random number
    private int drawNumber() {
        return random.nextInt(maxNum) + 1;
    }

    // Function to randomly draw six numbers using drawNumber() and store in an array
    int[] draw() {
        int[] drawnNums = {0, 0, 0, 0, 0, 0};
        for (int i = 0; i < drawnNums.length; i++) {
            int draw = drawNumber();
            drawnNums[i] = draw;
        }

        // Check if there are any duplicates in the array, if there are, redraw
        int numOfDuplicates = 0;
        for (int x = 0; x < drawnNums.length; x++) {
            int numToCheck = drawnNums[x];
            numOfDuplicates = 0;
             for (int y = 0; y < drawnNums.length; y++) {
                if (numToCheck == drawnNums[y]) {
                    numOfDuplicates++;
                }
                if (numOfDuplicates >= 2) {
                    draw();
                }
            }
            break;
        }

        return drawnNums;
    }
}

I expect that if there are duplicates in the array, the numbers will be redrawn until there is an array with no duplicates. But when running the program repeatedly, there are still some arrays with duplicates in them.

Your recursive call to draw is not returning a value. Should be

return draw();

The outer check loop exits early without completely checking the entire array for duplicates, remove the break. Check if x==y in the inner loop, do the duplicate check only if they are not.

Or in java 8, use a one liner to replace the entire thing.

new Random().ints(start, end).distinct().limit(number).toArray();

Ref - Random number generator without replacement?

3 Ways to Find Duplicate Elements in an Array - Java, How do I remove duplicates from an array in place? Since you're not sorting your array in advance, you're not guaranteed that the position of the duplicate numbers will be next to one another. Solution would be to either sort the array first then run your code. Merge or quick sort will get you nlog(n) complexity.

You want to check for duplicates within your returnable Array before you add to it. In other words, as soon as the draw variable receives a new random value see if that value is already contained within the drawnNums array:

private int[] draw() {
    int[] drawnNums = {0, 0, 0, 0, 0, 0};
    boolean alreadyHave;
    for (int i = 0; i < drawnNums.length; i++) {
        int draw = drawNumber();
        alreadyHave = false;
        for (int j = 0; j < drawnNums.length; j++) {
            if (draw == drawnNums[j]) {
                alreadyHave = true;
                i--;
                break;
            }
        }
        if (!alreadyHave) {
            drawnNums[i] = draw;
        }
    }
    return drawnNums;
}

Program to remove Duplicate Elements in an Array, How do you find duplicate numbers in an array if it contains multiple duplicates? This version does not need a temp array for storing the result temporary, but I think its a bit more readable (potentially an opinion). The downside is that it will transverse the input array when populating the result array, while yours only iterates returnArray.length

If you want uniqueness, it's easiest to use a container that gives you uniqueness.

int[] draw() {
    final int COUNT = 6;
    // get unique numbers
    Set<Integer> nums = new HashSet<>();
    while (nums.size() != COUNT)
        nums.add(drawNumber());
    // convert to array as per original requirements
    // though it would be simpler if we could just
    // return a Collection<Integer>
    int[] result = new int[COUNT];
    int k = 0;
    for (Integer num : nums)
       result[k] = num;
    return result;
}

Simpler, by a change of return type, with no loss of usefulness to the caller:

Collection<Integer> draw() {
    final int COUNT = 6;
    Set<Integer> nums = new HashSet<>();
    while (nums.size() != COUNT)
        nums.add(drawNumber());
    return nums;
}

Remove duplicates from sorted array, How are duplicates removed from a given array in C? There are multiple ways to remove duplicates from an array. The simplest approach (in my opinion) is to use the Set object which lets you store unique values of any type. In other words, Set will automatically remove duplicates for us.

Lessons in Scientific Computing: Numerical Mathematics, Computer , Below is a program to find and remove any duplicate element present in the specified array. #include<stdio.h> #include<conio.h> void  Java program to remove duplicate elements from an array In this java program, we are going to read an array and removing the duplicate elements from it . Submitted by Preeti Jain , on March 13, 2018

Classical Fortran: Programming for Engineering and Scientific , Given a sorted array, the task is to remove the duplicate elements from the array. Simple C++ program to remove duplicates If current element is not equal. We know that HashSet doesn’t allow duplicate values in it. We can make use of this property to check for duplicates in an array. The idea is to insert all elements of the array into a HashSet. Now the array contains a duplicate if length of the array is not equal to size of the set.

New Perspectives on HTML 5 and CSS: Comprehensive, low performance high performance do j=1,N do i=1,N freq2=sqrt(1. The same holds true for statements that cause a function or program to Error, stop, or exit statements often—not always, but often—, demand that the program exits at passed is the address of the first element, so this does not create a duplicate array. Problem. Find a duplicate in an array; Given an array of n + 1 integers between 1 and n, find one of the duplicates. If there are multiple possible answers, return one of the duplicates.

Comments
  • Maybe you want return draw(); but I would think a better way would be the check the value before adding it to the array.
  • for (int y = 1; y < drawnNums.length; y++) {
  • there are many better ways to achieve what you are trying here, but the issue in your code is that break; you are breaking only after checking for duplicates for first element in the array.
  • Check for duplicates before you add the random value in draw to the drawnNums Array.
  • This method works in stopping duplicates from being added to the array, but it then just leaves the value at that index at 0, how would I draw another number in place of that and check it?
  • With the code before the last edit -- the outer loop could be for (int i; i<6; ), and the if (!alreadyHave) clause would also increment i: drawnNums[i++] = draw