Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Detecting duplicate numbers in an array

$
0
0
I am trying to detect duplicate numbers in an array. If there are duplicates then it should return false, but if each number in the list is different then it should return true. The problem it that it gives me either true or false for both cases. I know why it does this, which is because of the if statement on line 17, however I do not know what to do about it. If I take out the line 17 if statement then the problem simply shifts to another place in the code. The problem occurs when the two variables, index2 and endLine, are equivalent. My basic approach to the problem is to take the number at the 0th position in the array and compare it to the number in 1st position, then the 2nd, 3rd, 4th, and so on. I have called this constantly increasing variable index1 (that's index "one" not index "L"). When I reach the end of the array, meaning when index1 and endList are the same I set index1 to index2+1 so that it is always one position ahead in the list and repeat the loop. As I have stated previously, the problem occurs when index2 and endLine are the same. Any help or suggestions would be appreciated, sorry for the length of the description.

import java.util.Arrays;

public class DistinctCheck {
    public static boolean areDistinct(int[] a) {
        int index1=1;
        int index2=0;
        int endList=a[a.length-1];
        
        while(index2<=a.length){ 
            if(a[index1]==a[index2]){
                return false;
            }
            else if(endList==a[index1]){
                index2++;
                index1=index2+1;
                
                if((endList-index2)==1){
                    return true;
                }
            }
            else{
                index1++;
                
            }
        
       // FILL IN CODE HERE
    }
    return true;
}

    
    
    
    public static void printIntArray(int[] a) {
        System.out.println(Arrays.toString(a));
       // FILL IN CODE HERE
    }
    
    public static void main(String[] args) {
        int[] a1 = {1,2,3,4,5,6,7,8,9};
        System.out.println("First array is printed below: ");
        printIntArray(a1);
        System.out.println("areDistinct for first array: " + areDistinct(a1));
        
        int[] a2 = {1,3,5,7,6,4,3,2};
        System.out.println("Second array is printed below: ");
        printIntArray(a2);
        System.out.println("areDistinct for second array: " + areDistinct(a2));
    }
}


Please disregard my comment "FILL IN CODE HERE" that was a note to myself when I began.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>