4

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.

4 Answers 4

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

4

When you call your method recursivelym you don't store its return value, effectively losing the indicator whether or not the character was found. What you actually want to do is return the results up to the recursive call above the current one.

try this:

private static boolean findSequenceRecHelper(char [] findIn, char c, int index)
{
    boolean result = false;
    if(index<findIn.length)
    {
        if(findIn[index] == c)
            return true;
        else
            return findSequenceRecHelper(findIn,c,index+1);
    }
}

Comments

0

Change this:

if(index<findIn.length)
{
    if(findIn[index] == c)
        result = true;
    else
        return findSequenceRecHelper(findIn,c,index+1);
}

Comments

0

You're not doing anything with your recursive call. Instead, you'll want to set what it returns to result, so that you may recursively return it, ie. result = findSequenceRecHelper(findIn,c,index+1); inside your if statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.