Is this the right way to use recursion? - c++

Given strings s and t compute recursively, if t is contained in s return true.
Example: bool find("Names Richard", "Richard") == true;
I have written the code below, but I'm not sure if its the right way to use recursion in C++; I just learned recursion today in class.
#include <iostream>
using namespace std;
bool find(string s, string t)
{
if (s.empty() || t.empty())
return false;
int find = static_cast<int>(s.find(t));
if (find > 0)
return true;
}
int main()
{
bool b = find("Mississippi", "sip");
string s;
if (b == 1) s = "true";
else
s = "false";
cout << s;
}
If anyone find an error in my code, please tell me so I can fix it or where I can learn/read more about this topic. I need to get ready for a test on recursion on this Wednesday.

The question has changed since I wrote my answer.
My comments are on the code that looked like this (and could recurse)...
#include <iostream>
using namespace std;
bool find(string s, string t)
{
if (s.empty() || t.empty())
return false;
string start = s.substr(0, 2);
if (start == t && find(s.substr(3), t));
return true;
}
int main()
{
bool b = find("Mississippi", "sip");
string s;
if (b == 1) s = "true";
else
s = "false";
cout << s;
}
Watch out for this:
if (start == t && find(s.substr(3), t));
return true;
This does not do what you think it does.
The ; at the end of the if-statement leaves an empty body. Your find() function will return true regardless of the outcome of that test.
I recommend you turn up the warning levels on your compiler to catch this kind of issue before you have to debug it.
As an aside, I find using braces around every code-block, even one-line blocks, helps me avoid this kind of mistake.
There are other errors in your code, too. Removing the magic numbers 2 and 3 from find() will encourage you to think about what they represent and point you on the right path.
How would you expect start == t && find(s.substr(3), t) to work? If you can express an algorithm in plain English (or your native tongue), you have a much higher chance of being able to express it in C++.
Additionally, I recommend adding test cases that should return false (such as find("satsuma", "onion")) to ensure that your code works as well as calls that should return true.
The last piece of advice is stylistic, laying your code out like this will make the boolean expression that you are testing more obvious without resorting to a temporary and comparing to 1:
int main()
{
std::string s;
if (find("Mississippi", "sip"))
{
s = "true";
}
else
{
s = "false";
}
std::cout << s << std::endl;
}
Good luck with your class!

Your recursive function needs 2 things:
Definite conditions of failure and success (may be more than 1)
a call of itself to process a simpler version of the problem (getting closer to the answer).
Here's a quick analysis:
bool find(string s, string t)
{
if (s.empty() || t.empty()) //definite condition of failure. Good
return false;
string start = s.substr(0, 2);
if (start == t && find(s.substr(3), t)); //mixed up definition of success and recursive call
return true;
}
Try this instead:
bool find(string s, string t)
{
if (s.empty() || t.empty()) //definite condition of failure. Done!
return false;
string start = s.substr(0, 2);
if (start == t) //definite condition of success. Done!
return true;
else
return find(s.substr(3), t) //simply the problem and return whatever it finds
}

You're on the right lines - so long as the function calls itself you can say that it's recursive - but even the most simple testing should tell you that your code doesn't work correctly. Change "sip" to "sipx", for example, and it still outputs true. Have you compiled and run this program? Have you tested it with various different inputs?

You are not using recursion. Using std::string::find in your function feels like cheating (this will most likely not earn points).
The only reasonable interpretation of the task is: Check if t is an infix of s without using loops or string functions.
Let's look at the trivial case: Epsilon (the empty word) is an infix of ever word, so if t.empty() holds, you must return true.
Otherwise you have two choices to make:
t might be a prefix of s which is simple to check using recursion; simply check if the first character of t equals the first character of s and call isPrefix with the remainder of the strings. If this returns true, you return true.
Otherwise you pop the first character of s (and not of t) and proceed recursively (calling find this time).
If you follow this recipe (which btw. is easier to implement with char const* than with std::string if you ask me) you get a recursive function that only uses conditionals and no library support.
Note: this is not at all the most efficient implementation, but you didn't ask for efficiency but for a recursive function.

Related

What is the most efficient way to return results from recursion?

There are 2 possible ways that I am familiar with while returning a boolean/integer value from a recursive function that defines is the operation carried out was a success or not.
Using static variables inside the recursive function. Changing values in the recursive calls and then returning the final value once everything is done.
Passing the result variable by reference to the recursive function and then manipulating its values in the function and then checking if the value corresponds to the result or not.
void Graph::findPath(string from, string to)
{
int result = 0;
if (from == to) cout<<"There is a path!"<<endl;
else
{
findPathHelper(from, to, result);
if (result) cout<<"There is a path!"<<endl;
else cout<<"There is not a path!"<<endl;
}
}
void Graph::findPathHelper(string from, string toFind, int &found)
{
for (vector<string>::iterator i = adjList[from].begin(); i != adjList[from].end(); ++i)
{
if (!(toFind).compare(*i))
{
found = 1;
break;
}
else
findPathHelper(*i, toFind, found);
}
}
Is there a better way to achieve this?
Thank You
I have changed your implementation to use a return value
bool Graph::findPathHelper(const string& from, const string& toFind)
{
for (vector<string>::iterator i = adjList[from].begin(); i != adjList[from].end(); ++i)
{
// I have assumed you comparison was incorrect - i.e. toFind == *i is that you want
// toFind == *i - The two strings are equal - Thus found
// or
// Recurse on *i - Have we found it from recursion
if (toFind == *i || findPathHelper(*i, toFind)) {
return true;
}
}
// We have searched everywhere in the recursion and exhausted the list
// and still have not found it - so return false
return false;
}
You can return a value in the recursive function and use that returned value for checking if it was success or not in subsequent calls.
Using static variable for this purpose may work but it's generally not a good IDEA and many consider it as bad practice.
Look into the below link which explains why we must avoid static or global variables and what kind of problems it could lead to during recursion.
http://www.cs.umd.edu/class/fall2002/cmsc214/Tutorial/recursion2.html
Note: I do not have enough reputation still to make a comment; and therefore i have posted this as answer.

Is there a way of doing a "post switch" like operation with bool?

I have a condition like the following where I just want to have the second bool be the trigger for a single time, since this condition is invoked relatively often I don't like the idea of doing the assignment of it being false every time the condition is true so, I tried to take advantage of the order of logical AND and OR and the post increment operator. But it appears to work don't do what I expected it to do. So is there a way to make a post state switch for this line?
where firstTitleNotSet is:
bool firstTitleNotSet;
if (titleChangedSinceLastGet() || (p_firstTitleNotSet && p_firstTitleNotSet++))
The idea is that the first part is the primary trigger and the second is the trigger that only has to trigger the first time.
While I easily could do
if (titleChangedSinceLastGet() || p_firstTitleNotSet)
{
firstTitleNotSet = false;
//...
}
I don't like this as it is reassigning false when ever the conditional block is invoked.
So is there some way of "post change" the value of a bool from true to false? I know that this would work the other way around but this would negate the advantage of the method most time being the true trigger and therefor skipping the following check.
Note: The reasons for me making such considerations isntead of just taking the second case is, that this block will be called frequently so I'm looking to optimize its consumed runtime.
Well, you could do something like:
if (titleChangedSinceLastGet() ||
(p_firstTitleNotSet ? ((p_firstTitleNotSet=false), true):false))
An alternative syntax would be:
if (titleChangedSinceLastGet() ||
(p_firstTitleNotSet && ((p_firstTitleNotSet=false), true)))
Either one looks somewhat ugly. Note, however, that this is NOT the same as your other alternative:
if (titleChangedSinceLastGet() || p_firstTitleNotSet)
{
p_firstTitleNotSet = false;
//...
}
With your proposed alternative, pontificate the fact that p_firstTitleNotSet gets reset to false no matter what, even if the conditional was entered because titleChangedSinceLastGet().
A more readable way than the assignment inside a ternary operator inside an or inside an if would be just moving the operations to their own statements:
bool needsUpdate = titleChangedSinceLastGet();
if(!needsUpdate && firstTitleSet)
{
needsUpdate = true;
firstTitleSet = false;
}
if(needsUpdate)
{
//...
}
This is likely to produce very similar assembly than the less readable alternative proposed since ternary operators are mostly just syntactic sugar around if statements.
To demonstrate this I gave GCC Explorer the following code:
extern bool first;
bool changed();
int f1()
{
if (changed() ||
(first ? ((first=false), true):false))
return 1;
return 0;
}
int f2()
{
bool b = changed();
if(!b && first)
{
b = true;
first = false;
}
return b;
}
and the generated assembly had only small differences in the generated assembly after optimizations. Certainly have a look for yourself.
I maintain, however, that this is highly unlikely to make a noticeable difference in performance and that this is more for interest's sake.
In my opinion:
if(titleChangedSinceLastUpdate() || firstTitleSet)
{
firstTitleSet = false;
//...
}
is an (at least) equally good option.
You can compare the assembly of the above functions with this one to compare further.
bool f3()
{
if(changed() || first)
{
first = false;
return true;
}
return false;
}
In this kind of situation, I usually write:
bool firstTitleNotSet = true;
if (titleChangedSinceLastGet() || firstTitleNotSet)
{
if (firstTileNotSet) firstTitleNotSet = false;
//...
}
That second comparison will likely be optimized by the compiler.
But if you have a preference for a post-increment operator:
int iterationCount = 0;
if (titleChangedSinceLastGet() || iterationCount++ != 0)
{
//...
}
Note that this will be a problem if iterationCount overflows, but the same is true of the bool firstTitleNotSet that you were post-incrementing.
In terms of code readability and maintainability, I would recommend the former. If the logic of your code is sound, you can probably rely on the compiler to do a very good job optimizing it, even if it looks inelegant to you.
That should work:
int firstTitleSet = 0;
if (titleChangedSinceLastGet() || (!firstTitleSet++))
If you wish to avoid overflow you can do:
int b = 1;
if (titleChangedSinceLastGet() || (b=b*2%4))
at the first iteration b=2 while b=0 at the rest of them.

Is there a way to replace string ">" with > in an 'if' condition?

I came across the below use case, but I could not find a proper solution.
Is there a way to replace string "<" or ">" with condition < or > in an if condition?
Example:
string condition = "<";
if (10 condition 8) // Here I want to replace condition with <
{
// Some code
}
I don't want to do it like:
if ("<" == condition)
{
if (10 < 8)
{
}
}
else if (">" == condition)
{
if (10 > 10)
{
}
}
And my condition will change during run time. I am just searching for a simple way if exist apart from above.
Use case: The user will give some query like below:
input: 10 > 9 => output: true
input: 10 < 7 => output: false
Basically I need to parse this query, as I have these 3 words (10, >, 9) as strings, and somehow I want to convert string ">" or "<" to actual symbol > or <.
You can map the string to a standard library comparator functor such as std::less via a std::map or a std::unordered_map.
You can't create a new operator in C++ (Can I create a new operator in C++ and how?). I can see where you are coming from with this idea, but the language just doesn't support that. You can, however, create a function that takes two operands and a string "argument" and returns the appropriate value.
bool CustomCompare(int operand1, int operand2, string op)
{
if (op == "<")
{
return operand1<operand2;
}
if (op == ">")
{
return operand1>operand2;
}
if (op == "_")
{
return DoTheHokeyPokeyAndTurnTheOperandsAround(operand1, operand2);
}
}
std::function<bool(int,int)> comparator = std::less;
if(comparator(10, 8))
{
//some code
}
See Also:
http://en.cppreference.com/w/cpp/utility/functional/function
http://en.cppreference.com/w/cpp/utility/functional/less
#include <functional>
#include <map>
#include <string>
int main()
{
using operation = std::function<bool(int,int)>;
std::map<std::string, operation> mp =
{{"<", std::less<int>()},
{">", std::greater<int>()}};
int x = 5;
int y = 10;
std::string op = "<";
bool answer = mp[op](x, y);
}
If you are a C++ Ninja, and you are very stubborn to get it working just the way you wish, there is a way, but it is advanced and complicated.
I mostly write POSIX code for VxWorks, but I guess it can be done for any other.
Let's say you have: string myExpression = "mySize > minSize";
"Rebuild the String as a C code" (save to file, use ccppc, gcc, gpp, whatever toolchain you have.)
You need to link it with your code, at least to get ELF relocations for mySize & minSize (I think it can be done using app-load, if you customize your ld command.
Load the code using ld
Jump to the new address you loaded your code to.
All that said, I would not recommend you to do that:
Very complicated.
Not the most stable, and very bug/error prone.
Can lead to major vulnerabilities "Hacker" style,
and proper sanitation is required.
The only pro I can see, is that this method supports everything C has to offer out of the box! BitWise, +-/*^!, even functions as pow(), and such.
A little bit better is:
To compile a function as:
`"bool comparer_AB(int a, int b) { return a " + operator + "}"`
and then call comparer_AB();.

How are recursive backtracking returns handled with the void type

To generalize this question I am borrowing material from a Zelenski CS class handout. And, it is relevant to my specific question since I took the class from a different instructor several years ago and learned this approach to C++. The handout is here. My understanding of C++ is low since I use it occasionally. Basically, the few times I have needed to write a program I return to the class material, found something similar and started from there.
In this example (page 4) Julie is looking for a word using a recursive algorithm in a string function. To reduce the number of recursive calls she added a decision point bool containsWord().
string FindWord(string soFar, string rest, Lexicon &lex)
{
if (rest.empty()) {
return (lex.containsWord(soFar)? soFar : "");
} else {
for (int i = 0; i < rest.length(); i++) {
string remain = rest.substr(0, i) + rest.substr(i+1);
string found = FindWord(soFar + rest[i], remain, lex);
if (!found.empty()) return found;
}
}
return ""; // empty string indicates failure
}
To add flexibility to how this algorithm is used, can this be implemented as a void type?
void FindWord(string soFar, string rest, Lexicon &lex, Set::StructT &words)
{
if (rest.empty()) {
if (lex.containsWord(soFar)) //this is a bool
updateSet(soFar, words); //add soFar to referenced Set struct tree
} else {
for (int i = 0; i < rest.length(); i++) {
string remain = rest.substr(0, i) + rest.substr(i+1);
return FindWord(soFar + rest[i], remain, lex, words); //<-this is where I am confused conceptually
}
}
return; // indicates failure
}
And, how about without the returns
void FindWord(string soFar, string rest, Lexicon &lex, Set::StructT &words)
{
if (rest.empty()) {
if (lex.containsWord(soFar))
updateSet(soFar, words); //add soFar to Set memory tree
} else {
for (int i = 0; i < rest.length(); i++) {
string remain = rest.substr(0, i) + rest.substr(i+1);
FindWord(soFar + rest[i], remain, lex, words); //<-this is where I am confused conceptually
}
}
}
The first code fragment will try all permutations of rest, appended to the initial value of soFar (probably an empty string?). It will stop on the first word found that is in lex. That word will be returned immediately as it is found, and the search will be cut short at that point. If none were in lex, empty string will be returned eventually, when all the for loops have ran their course to the end.
The second fragment will only try one word: the concatenation of initial soFar and rest strings. If that concatenated string is in lex, it will call updateSet with it. Then it will return, indicating failure. No further search will be performed, because the return from inside the for loop is unconditional.
So these two functions are completely different. To make the second code behave like the first, you need it to return something else to indicate a success, and only return from within the for loop when FindWord call return value indicates a success. Obviously, void can not be used to signal failure and success. At the very least, you need to return bool value for that.
And without the returns your third code will perform an exhaustive search. Every possible permutation of initial string value of rest will be tried for, to find in the lexicon.
You can visualize what's going on like this:
FindWord: soFar="" rest=...........
for: i=... rest[i]=a
call findWord
FindWord: soFar=a rest=..........
for: i=... rest[i]=b
call findWord
FindWord: soFar=ab rest=.........
for: i=... rest[i]=c
call findWord
if return, the loop will be cut short
if not, the loop continues and next i will be tried
......
FindWord: soFar=abcdefgh... rest=z
for: i=0 rest[0]=z
call findWord
FindWord: soFar=abcdefgh...z rest="" // base case
// for: i=N/A rest[i]=N/A
if soFar is_in lex // base case
then do_some and return soFar OR success
else return "" OR failure
Each time the base case is reached (rest is empty) we have n+1 FindWord call frames on the stack, for n letters in the initial rest string.
Each time we hit the bottom, we've picked all the letters from rest. The check is performed to see whether it's in lex, and control returns back one level up.
So if there are no returns, each for loop will run to its end. If the return is unconditional, only one permutation will be tried - the trivial one. But if the return is conditional, the whole thing will stop only on first success.

Using local variables vs checking against function return directly

I have a function definition, where i call multiple functions. Even if one of the function fails i need to go ahead and call the rest of the functions and finally return a single error saying whether any of the function call failed. The approach which i had followed was
int function foo()
{
int res, res1, res2, res3;
res1 = function1();
res2 = function2();
res3 = function3();
if (res1 == -1 || res2 == -1 || res3 == -1)
{
res = -1;
}
return res;
}
The possible another approach is
int function foo()
{
int res;
if (function1() == -1)
{
res = -1;
}
if (function2() == -1)
{
res = -1;
}
if (function3() == -1)
{
res = -1;
}
return res;
}
Which is a better approach?
Thanks in advance.
No difference at all, both will be optimized to same machine code. Preference, maintainability, and that depends on team guidelines, preferences.
First priority, make the code correct. That's more important than readability and optimization.
That means you need to consider what the function should return in the case where the functions it calls all succeed.
Many of the answers given to this question change the result returned or might return a failure indication if the 'sub-functions' all succeed. you need to take care not to do this.
Personally, I think the overall form of your first option is pretty good - it makes clear that the 3 sub-functions are called regardless of whether one or more of them fail. The one problem is that it returns an indeterminate result if all those functions succeed.
Be wary of answers that use bitwise-or to combine results - there are at least 2 potential problems:
as John Marshall pointed out in several comments, the order of evaluation is indeterminate. This means that if you simply string the function calls with bitwise-or the functions may be called in any order. This might not be a problem if there are no ordering dependencies between the functions, but usually there are - especially if you don't care about the returned value except as a s success/fail indicator (if you aren't using the return value, then the only reason to call the function is for its side effects)
If the functions can return positive, non-zero values when they succeed, then testing for failure becomes a bit trickier than just checking if the results or'ed together are non-zero.
Given these two potential problems, I think there's little reason to try to do anything much fancier than option 1 (or your second option) - just make sure you set res to a success value (0?) for the situation where none of the sub-functions fail.
What about:
int foo ()
{
bool failed = false;
failed |= (function1() != 0);
failed |= (function2() != 0);
failed |= (function3() != 0);
return failed? -1 : 0;
}
You could also collapse the three calls into a single expression and omit the failed variable altogether (at the expense of readability):
int foo ()
{
return ((function1() != 0) | (function2() !=0 ) | (function3() != 0))? -1 : 0;
}
I like the first approach when function1 function2 and function3 have the same signature because I can put them in a function pointer table and loop over the entries, which makes adding function4 alot easier.
If you can define any precise convention about return values you can simply use bitwise or:
int foo() {
if (function1() | function2() | function3())
return -1;
else
return 0;
}
I like the second approach better. If you want one-liners, you can do something like...
char success = 1;
success &= (foo() == desired_result_1);
success &= (bar() == desired_result_2);
etc.
The 2nd is a "better" approach. However, I'd go more without the needless carrying around of an indicator variable:
if( function2() == -1 ){
return -1;
}
Suggestion: (no magic numbers)
I'd also not use "magic numbers" like you've used it. Instead:
if( check_fail( function2() ) ){
return FAILED;
}
more clearly illustrated what you're thinking. Intent is easier to maintain. Magic numbers can sometimes wind up hurting you. For instance, I've known financial guys who couldn't understand why a transaction costing "$-1.00" caused their application to behave abnormally.
In the first form you're not checking the status until all 3 calls are completed. I think this signals your intent the clearest. The second form more closely resembles the more usual case, where you return early if an error is detected.
It's a subtle thing either way. You shouldn't be asking us strangers on the internet, you should be asking the rest of your team, because they're the ones who will have to live with it.
You use bitwise operators to make a 'neat' variant that doesn't need temp variables and has other fancyness too(with the more advanced operators): return func1()|func2();(this is the same as using logical or, ||). However, if you require checking a specific function in the callee, you can create a bitset: return func1() << 1 | func2(); (this assumes that they return 1 or zero)
I'd vote for the second one as well.
This question reminded me of something similar I do in one of my projects for form validation.
I pass in a reference to an empty string. With each condition I want to check, I either add a line of text to the string, or I don't. If after every test the string is still empty, then there were no errors, and I continue processing the form. Otherwise, I print the string as a message box (which describes the problems), and ask the user to fix the errors.
In this case I don't really care what the errors are, just that there are errors. Oh, and as a bonus, my validation code documents itself a bit because the errors that the user sees are right there.
Use local variable if you need to reuse the result somewhere. Else, call and compare.
int foo() {
return function1() | function2() | function3();
}
Yet another option: pass a pointer to the status variable to each function and have the function set it only if there is an error.
void function1(int *res)
{
bool error_flag = false;
// do work
if (error_flag && (res != NULL)
{
*res = ERROR;
}
}
// similar for function2, function3, ...
int foo()
{
int res = OK;
function1(&res);
function2(&res);
function3(&res);
return res;
}
Since all 3 functions always have to get called first and only then you care about the result, I would go for the first solution, because the order of the statements reflects this. Seems more clear to me. Also, I generally don't like functions that do more than just return a value (i.e. that have side effects) in if-clauses, but that's a personal preference.
This sounds like a job for the abundant Perl idiom "<try something> || die()".
int foo() {
int retVal = 0;
function1() != -1 || retval = -1;
function2() != -1 || retval = -1;
function3() != -1 || retval = -1;
// ...
return retVal;
}
I write it this way:
int foo()
{
int iReturn = 0;
int res1 = function1();
if (res1 == -1)
{
return iReturn;
}
int res2 = function2();
if (res2 == -1)
{
return iReturn;
}
int res3 = function3();
if (res3 == -1)
{
return iReturn;
}
return res;
}
As a coding rule, you should declare your variables as close to the place where it is used.
It is good to use intermediate variable like your res1, res2, res3.
But choose a good name so as you intent is clear when you get the value from the function.
And be careful, in the example you've given us, you never assigned the int res; that may be returned when success. The coding rule is to initialize your variable as soon as you can.
So you should also initialize your res1 res2 res3 immidiatbly.
Returning an uninitialized value leads to undefined behaviour.
I've seen code like this before which might be a little cleaner:
bool result = true;
result = function1() == -1 && result;
result = function2() == -1 && result;
result = function3() == -1 && result;
return result?-1:0;
Edit: forgot about short circuiting.