|
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.
|