# FInd the no. of duplicates in an array

Printable View

• 09-04-2009, 08:33 AM
singularity
FInd the no. of duplicates in an array
I needto find the no. of duplicates in the array. There seems to be something wrong with the loops. Can anyone see where I am wrong in looping.
Thanks. Your help is greatly appreciated:

Quote:

public class duplicate {
int temp, true_count;
int ar[] = { 1, 2, 3, 4, 1 };
int count;

public void find() {
for (int i = 0; i < ar.length - 1; i++) {
temp = ar[i];
for (int j = i; j <= ar.length-1 ; j++) {

if (temp == ar[j]) {

count += 1;
}

}

}
}

public static void main(String args[]) {
duplicate dup = new duplicate();
dup.find();

System.out.println("The No of duplicates is :" + dup.count);

}

}
• 09-04-2009, 08:50 AM
r035198x
This has been done many times and the trick is to use a HashMap.
You just go through the array once and at each index you get the current value in the array and get it from the hashmap using itself as the key. If you get null from the map then the key is not there and you put it in setting it's value to 1. Otherwise increment it's value.
At the end of that loop you'll have a Map with the keys being the array elements and the values being the number of times each element appears in the array.
• 09-04-2009, 09:08 AM
singularity
DO You mean to say it is not possible to do it with arrays: I execute the code but it gives correct results in some cases amd wrong results in most of the cases:
Here is my code and various results:
Quote:

public class duplicate {
int temp;
int ar[] = { 2, 2, 3, 4, 2 };
int count;

private void find() {
for (int i = 0; i < ar.length - 1; i++) {
temp = ar[i];
for (int j = i+1; j <= ar.length -1; j++) {

if (temp == ar[j]) {

count += 1;
}
}
}
}

public static void main(String args[]) {
duplicate dup = new duplicate();
dup.find();

System.out.println("The No of duplicates is :" + dup.count);

}

}

OutPUT: The No of duplicates is :3 // Correct
If int ar[] = { 1, 2, 3, 4, 2 }; then output is:
The No of duplicates is :1// wrong should be 2
if int ar[] = { 1, 2, 3, 4, 1 }; then output is:
The No of duplicates is :1// wrong should be 2
if int ar[] = { 1, 1, 3, 4, 1 }; then output is:
The No of duplicates is :3//right
if int ar[] = { 1, 2, 3, 3, 1 } then output is:
The No of duplicates is :2// right
if int ar[] = { 3, 2, 4, 3, 1 }; then output is:
The No of duplicates is :1// should be 2
And so on......

Most IMpt:
If int ar[] = { 4, 4, 4, 4, 4 };
Then Output is:
The No of duplicates is :10
• 09-04-2009, 09:25 AM
r035198x
The problem is that with 5 fours, after the first 4 is found, the rest of the fours are considered as having duplicates too. The map takes care of all that for you.