# HELP: Trouble with partial filled arrays

• 04-06-2008, 07:59 PM
daigre7
HELP: Trouble with partial filled arrays
For HW, I have to write a deleteRepeats static method for an array of characters that deletes any character previously listed and returns the new array size. The example the problem gives is:

char a[10];
a[0]='a';
a[1]='b';
a[2]='a';
a[3]='c';
int size = 4;
size = deleteRepeats(a, size);

The problem then says after the code is executed, a[0] should be 'a', a[1] should be 'b', a[2] should be 'c' and size is 3. I read the section in my book on partially filled arrays, but I still can't get this method to work properly. Here is my code:

public static int deleteRepeats(char[] a, int size) {

size=a.length;
int numberOfRepeats=0;

for(int i=0; i<size; i++) {
for(int j=1; i+j<size; j++) {
if(a[i]==a[i+j]) {
a[i+j]=a[(i+j)+1];
size--;
numberOfRepeats++;

}
}
}
return size;
}

With that code, when I put in the test array [aabcd], it returns 3, when it should be 4 and it changes the array to [abccd]. I'm sure there's numerous problems with my code. Any help is greatly appreciated.
• 04-07-2008, 02:05 AM
daigre7
BTW, we're learning about ArrayLists now, but we can't use them for this HW. He wants us to learn how to do something like this without it.

I know that to remove an element in an array you have to do something like shift everything with a higher index to the left and then transfer what you want to a new array of size one less than the original, but I have trouble figuring out the code that does that. Just read the part before my code and let me know how you would go about writing such a method.