Reputation: 141
Langauge: Java
No syntax errors and passed the compiler but failed my tester. Anyone can tell me what I did wrong here?
Here's what the lab text states for what the method is to do: "counts how many runs (consecutive blocks of equal elements) there are in the subarray of arr from index start to index end , inclusive"
Also: I'm not allowed to use any loops for this lab, if-else statements are okay though.
parameters: arr = array, start/end = indices for start/end
public class Recursion {
int countRuns(int[] arr, int start, int end) {
if (start >= end)
return 0; //checks for null arrays
int counter = 0;
if (start == 0)
counter = 1;
//check the next element for similarity/difference
if (arr[start] != arr[start+1])
counter = 1;
return counter + countRuns(arr, start + 1, end);
}
}
Upvotes: 0
Views: 416
Reputation: 2897
I think you just slightly missed the conditions at beginning and end.. This should work:
public class Recursion {
int countRuns(int[] arr, int start, int end) {
if (start > end)
return 0; //checks for null arrays
if (start == end) // the indices are inclusive
return 1;
int counter;
if (arr[start] == arr[start + 1]) {
counter = 0; // we'll still be in the same run, if they're equal
} else {
counter = 1; // otherwise it's a new run
}
return counter + countRuns(arr, start + 1, end);
}
}
Upvotes: 3