I am working on understanding recursion, and I think I have it down alright… I’m trying to build a search function (like the std::string.find()) that searches a given string for another string for example:
Given (big) string: “ru the running cat”
search (small) string: “run”
I’m trying to return a index for the where the word i am searching for (in the case above it would be **7) the recursive method i have is as follows – i can’t seem to get it to return the index properly.
calling the recursive function:
index = index_of(imput.c_str(), search.c_str())
Recursion method:
int index_of( const char * i, const char * s) {
int j;
if (*s == '\0') { return; }
if (*i == '\0') {
return NULL;
}
else if ( *i == *s ) {
index_of((i++), (s++));
}
else {
j += index_of((i++), s);
}
return j;
}
another foreseeable problem is that when (like in the example – OK it sucks but i need one that worked) it reaches the “ru_” it’s still stuck on the ‘ ‘ (SPACE) -> how would i get it to ‘reset’ the s pointer?
++anywhere. You are not trying to loop over a datastructure and change your local variables in some fashion – you are trying to generate an entirely new but smaller problem each time. So, all those++operators – whether pre or post increment – are red flags.You have more than one sub-problem. (…so single function recursion isn’t ideal).
Let’s look at this systematically.
Assume you have a working
index_ofand you just want to call it with input that’s shorter than yours, and that both haystack and needle aren’t empty yet. Then one of two things may be:The haystack starts with the same letter as the needle, and you just need to look a little deeper to verify this.
– What happens if verification succeeds – what if it fails? is this an
index_ofsubproblem?…or the haystack starts off wrong, and you need to look deeper.
– Is looking deeper into the haystack an index_of subproblem?
Notice that if the haystack starts OK it doesn’t necessarily mean that it starts with the full search string – and if it starts OK but does not start with the full search string, you really don’t need to continue looking. That means that the “starts-with” sub-problem is fundamentally different than the index-of sub-problem:
It is possible to say
startswith(haystack, needle):= 0==index_of(haystack, needle), but obviouslyindex_ofis a more complicated problem with a more expensive solution – so you shouldn’t do that; it’s also more confusing at first.Identify your base cases – When either needle or haystack are empty, what does that mean?
Good names help clarify things, and recursion is hard to read at the best of times – Yacoby’s reply for instance has some meaningful choices here.
Summary
I’m not going to solve your own puzzle for you, but a few tips in recap…
AcallingA– it can be any cyclic call graph that eventually terminates; you may use more functionsif (*s == '\0') { return 1; }