While we're still skinning this cat, here are a couple more ways.
First a modified version of what I posted earlier. It's forward looking and that eliminated the need for the initial array length check - the main loop does the check. Also changed the for loop that increments the pointer to a while loop to make it more clear.
Code:
public static int countRepeats(int[] a)
{
int repeated, count = 0;
for(int i = 0; i < a.length-1; )
{
if (a[i] == a[++i])
{
count++;
repeated = a[i++];
while(i < a.length-1 && a[i] == repeated) i++;
}
}
return count;
}
Can someone with more Java/C experience comment on the use of postfix and prefix operators above? I'm learning C++ at the moment and see them all the time in others' code, but I'm not sure how idiomatic they are. I'm particularly leery about the line:
Code:
if (a[i] == a[++i])
Here's a partially recursive version (it still has a while loop).
Code:
public static int countRepeats3_r(int[] a, int start, int end, int count)
{
if (end-start <= 1)
return count;
if (a[start] == a[start+1])
{
int next = start+2;
while(next < end && a[next] == a[start]) next++;
return countRepeats3_r(a, next, end, count+1);
}
else
return countRepeats3_r(a, start+1, end, count);
}
public static int countRepeats3(int[] a)
{
return countRepeats3_r(a, 0, a.length, 0);
}
I tried a fully recursive version, but it was a bit ugly for my liking.