Checking for duplicate numbers in an arbitrary array

I have an array filled with random numbers. I want to check if there are duplicate numbers in the array, but I am having problems. This is what I have so far:

Random randomNum=new Random();        
int[] array = new int[100];
for(int i = 0; i <  array.length; i++) {
    array[i] = randomNum.nextInt(100); //0-99
    System.out.print(array[i] + "  ");
}

for(int index = 0; index < array.length; index++) {
    if(array[index] == array[index+1])
    System.out.println("Match in"+array[index]);
}

      

+3


source to share


2 answers


Your code failed because you tried to access an element after the last one in the array: the last one matters array[array.length - 1]

, but you've tried it array[array.length]

when called array[index+1]

, and your index is already the last one array.length - 1 + 1

= array.length

. To fix this, just go to the prelast element.

Random randomNum=new Random();        
 int[] array = new int[100];
 for(int i = 0; i <  array.length; i++) {
    array[i] = randomNum.nextInt(100); //0-99
    System.out.print(array[i] + "  ");
 }

for(int index = 0; index < array.length - 1; index++)
{
  if(array[index] == array[index+1]) 
  {
    System.out.println("Match in "+array[index]);
  }
}

      



But I think this code will not solve your problem because it will only find duplicate neighbors. If you want all the duplicates, you need a double loop:

Random randomNum=new Random();        
 int[] array = new int[100];
 for(int i = 0; i <  array.length; i++) {
    array[i] = randomNum.nextInt(100); //0-99
    System.out.print(array[i] + "  ");
 }

for(int i = 0; i < array.length; i++)
{
  for(int j = i+1; j < array.length; j++) {
    if(array[i] == array[j]) {
      System.out.println("Match in "+array[i]);
    }
  }
}

      

+3


source


You can use HashSet to find duplicate values ​​as it does not accept duplicates.



    Random randomNum = new Random();
    int[] array = new int[100];
    for (int i = 0; i < array.length; i++) {
        array[i] = randomNum.nextInt(100); // 0-99
        System.out.print(array[i] + "  ");
    }
    Set<Integer> rnd = new HashSet<Integer>();
    for (int i : array) {
        if (!rnd.add(i)) {
            System.out.println(i + " is a duplicate");
        }
    }

      

+3


source







All Articles