Click here to Skip to main content
15,909,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
CSS
I have taken array int[] a = {33,33,5,5,9,8,9,9};
In this array so many values are duplicates means 33 comes twice & 5 also comes twice & 9 comes three times. But I want to count the first value which is duplicate means 33 is first value which comes twice so answer would be 2.

I try:


C#
public class FindFirstDuplicate
{

public static void main(String[] args) {

    int c=0;
    int[] a = {33,33,5,5,9,8,9,9};

    outerloop:
    for(int i = 0; i < a.length; i++)
    {
        for(int j = i+1; j< a.length; j++)
        {
            if(a[i] == a[j])
            {
                System.out.println(a[i]); //Duplicate value
                c++;
                break outerloop;
            }
        }

    }
    System.out.print("Count: "+c);

    }
}
Output: 33 
Count: 1
Posted

You are almost there,
1. One mistake, when the first duplicate found, => c=2
2. Once the first pair found, start a loop to count the remaining duplicates.
Insert the following code to your original one:
Java
// ...
if(a[i] == a[j])
{
    System.out.println(a[i]); //Duplicate value

    // Duplicate means there are at least 2
    c = 2;
    // Once the first pair found, loop to
    // count the number of remaining duplicates
    for(int k = j+1; k < a.length; k++){
        if(a[j] == a[k]){
            c++;
        }
    }
    break outerloop;
// ...
 
Share this answer
 
v3
don't break inside the inner loop, let inner loop finish and count all the duplicates and after the loop check for duplicate count and break the loop
Java
for(int j = i+1; j< a.length; j++)
{
 if(a[i] == a[j])
 {
     System.out.println(a[i]); //Duplicate value
     c++;   
 }
}
if(c>0) // duplicate found 
{
   break outerloop;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900