# Thread: Array Help - Finding and replacing duplicate cells

1. Member
Join Date
Sep 2010
Posts
56
Rep Power
0

## Array Help - Finding and replacing duplicate cells

This method is designed to check an integer array for duplicates. It will compile and run but the logic is flawed somewhere.

The method is designed to find duplicates and replace them with another random number, and continue until no more duplicates are found.

Java Code:
```public static void checkDuplicates(int[] a)
{
int[] num = new int[a.length + 1];
boolean done = false;

for(int e = 0; e < a.length; e++)
{
num[a[e]]++;
}

while(done)
{
done = false;

for(int e = 0; e < a.length; e++)
{
num[a[e]]++;
}

for(int e = 0; e < num.length - 1; e++)
{
if(num[e] == 2)
{
num[e]--;
int index = search(a, e);
a[index] = gen.nextInt(25) + 1;
done = true;
}
}

for(int e = 0; e < num.length; e++)
{
num[e] = 0;
}
}
}

public static int search(int[] a, int value)
{
int e;

for(e = 0; e < a.length; e++)
{
if(a[e] == value)
break;
}

return e;
}```
Thanks in advance for the help!

AB
Last edited by javaman1; 02-05-2011 at 02:33 AM.

2. Senior Member
Join Date
Apr 2010
Location
Philippines
Posts
580
Rep Power
11
What is the expected output?
and what is the actual output?

3. Member
Join Date
Sep 2010
Posts
56
Rep Power
0
The input is a 25 cell array with random numbers up to 25.
The expected output is the numbers 1 through 25. NO duplicates.
The actual output does not change after the method is run. It is the same as the input.

4. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18
Java Code:
```boolean done = false;

for(int e = 0; e < a.length; e++)
{
num[a[e]]++;
}

while(done)
{
// etc...```

That can't be right. done is false so the while loop will never get executed.

5. Member
Join Date
Dec 2010
Posts
2
Rep Power
0
for(int e = 0; e < a.length; e++)
{
num[a[e]]++;
}
this code is not correct, you can get OutOfArraySizeException

6. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18
you can get OutOfArraySizeException

Do you mean ArrayIndexOutOfBoundsException? That won't happen because the OP has declared

Java Code:
`int[] num = new int[a.length + 1];`

and stated later that a.length is 25. So the array has 26 positions (indexed as 0 to 25).