I was asked to write something that would determine if an array is a subset of another larger array. I've decided to start with a simpler problem and written a function that will determine if a character present in an array of characters. I've came up with this code:
private static boolean findSequenceRecHelper(char [] findIn, char c, int index) {
boolean result = false;
if(index<findIn.length) {
if(findIn[index] == c) {
result = true;
}
else {
findSequenceRecHelper(findIn,c,index+1);
}
}
return result;
}
I've done some debugging and found that the function iterates through the whole char[]
array and when an element in array equals to desired value, result
turns to true
. But then again it turns to false
and false
is actually returned, which is incorrect.
I can't find an error here - can someone please help me with this problem.
In the recursive step:
else
findSequenceRecHelper(findIn,c,index+1);
You should return
the value returned by the recursive call. Otherwise - nothing is being done and the recursive call is actually redundant.
private static boolean findSequenceRecHelper(char [] findIn, char c, int index)
{
boolean result = false;
if(index<findIn.length)
{
if(findIn[index] == c)
result = true;
else
return findSequenceRecHelper(findIn,c,index+1);
//^
//added return here
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With