a way to test if you're on the first run of several recursive calls c++ - c++

I'm was wondering if there's a way to check if you're on the first recursive call of a series of many recursive calls.
I'm working on a function that tests to see if the input is a palindrome. After the last recursive call is over, the input string is changed to to the reverse of the original. Now all I want to do is compare the result with the original. But when the base case is reached, I no longer have access to the copy of the original string I made in the else statement.
My thought is then to compare palCopy with palCheck under the else statement but the problem with that is that the program will check this during EVERY recursive call when I only want to check it when control is returned to the original recursive call. Is there a way to conditionally compare palCopy and palCheck only when control is returned to the original recursive call?
void isAPalindrome(MyString palCheck, int bound1, int bound2)
{
if (bound1 >= bound2)
{
cout << palCheck;
}
else
{
MyString palCopy = palCheck; // make a copy of the original argument so as not to alter it
char temp = palCopy[bound1];
palCopy[bound1] = palCopy[bound2];
palCopy[bound2] = temp;
isAPalindrome(palCopy, bound1 + 1, bound2 - 1);
}

C++ has no primitive way to know if you are in the first recursion. But you could use a level variable, that counts the recursion depth. Something like:
void isAPalindrome(MyString palCheck, int bound1, int bound2, int level=0)
{
if (bound1 >= bound2)
cout << palCheck;
else
{
MyString palCopy = palCheck;
char temp = palCopy[bound1];
palCopy[bound1] = palCopy[bound2];
palCopy[bound2] = temp;
isAPalindrome(palCopy, bound1 + 1, bound2 - 1, level+1);
if (level == 0)
// You are in the first recursion call
}
}

In general you can track recursion depth by doing something like:
void recurse(int value, const int depth=0)
{
recurse(value, depth+1);
}
That is using an extra variable to for each of the calls which record the depth of recursion at any given point.

I wouldn't solve this problem this way, but never mind that. The general way to do something like this is to move the recursion into a helper function that takes an extra argument:
static void
is_palindrome_internal(string palCheck, int bound1, int bound2,
bool outermost)
{
...
is_palindrome_internal(..., false);
...
}
void
is_palindrome(string palCheck, int bound1, int bound2)
{
is_palindrome_internal(palCheck, bound1, bound2, true);
}
Then outermost will be true only when the current invocation is the outermost. This approach also has the advantage that you can hide the bound1 and bound2 arguments from the public API (only do this if you don't ever want to operate on substrings, of course).
void
is_palindrome(string palCheck)
{
is_palindrome_internal(palCheck, 0, palCheck.length(), true);
}

You are already passing one copy of string as an arg. You can also pass a reference to the original string so that all levels of recursion have access to both.
void isAPalindrome(MyString palCheck, int bound1, int bound2 , const MyString& original )
{
//Do stuff
isAPalindrome(palCopy, bound1 + 1, bound2 - 1,original);
}

I would use a local struct so that is_palindrome() will accept just one argument:
bool is_palindrome(const std::string& s)
{
struct local
{
static bool is_palin(const std::string& s, int l, int h)
{
return l>= h?true:(s[l] == s[h]? is_palin(s,l+1,h-1):false);
}
};
return local::is_palin(s, 0, s.size() - 1);
}
Online demo : http://www.ideone.com/o1m5C
Use and modify it whichever way you want to.

Make it a seperate function:
void isAPalindromeHelper(MyString& palCheck, int bound1, int bound2)
{
if (bound1 >= bound2)
{
cout << palCheck;
}
else
{
char temp = palCopy[bound1];
palCopy[bound1] = palCopy[bound2];
palCopy[bound2] = temp;
isAPalindromeHelper(palCopy, bound1 + 1, bound2 - 1);
}
}
void isAPalindrome(MyString palCheck)
{
MyString palCopy = palCheck;
isAPalindromeHelper(palCheck, 0, palCheck.size());
if (palCopy == palCheck)
//newstuff here
}

Related

function parameters that are writeable only by the function itself - recursion counter

So I'm trying to write a recursive function that keeps track of how often it got called. Because of its recursive nature I won't be able to define an iterator inside of it (or maybe it's possible via a pointer?), since it would be redefined whenever the function gets called. So i figured I could use a param of the function itself:
int countRecursive(int cancelCondition, int counter = 0)
{
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
Now the problem I'm facing is, that the counter would be writeable by the caller of the function, and I want to avoid that.
Then again, it wouldn't help to declare the counter as a const, right?
Is there a way to restrict the variable's manipulation to the function itself?
Or maybe my approach is deeply flawed in the first place?
The only way I can think of solving this, is to use a kind of "wrapper-function" that keeps track of how often the recursive function got called.
An example of what I want to avoid:
//inside main()
int foo {5};
int countToZero = countRecursive(foo, 10);
//countToZero would be 15 instead of 5
The user using my function should not be able to initially set the counter (in this case to 10).
You can take you function as is, and wrap it. One way I have in mind, which completely encapsulates the wrapping is by making your function a static member of a local class. To demonstrate:
int countRecursive(int cancelCondition)
{
struct hidden {
static int countRecursive(int cancelCondition, int counter = 0) {
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
};
return hidden::countRecursive(cancelCondition);
}
Local classes are a nifty but rarely seen feature of C++. They possess some limitations, but fortunately can have static member functions. No code from outside can ever pass hidden::countRecursive an invalid counter. It's entirely under the control of the countRecursive.
If you can use something else than a free function, I would suggest to use some kind of functor to hold the count, but in case you cant, you may try to use something like this using friendship to do the trick:
#include <memory>
class Counter;
int countRecursive(int cancelCondition, std::unique_ptr<Counter> counter = nullptr);
class Counter {
int count = 0;
private:
friend int countRecursive(int, std::unique_ptr<Counter>);
Counter() = default; // the constructor can only be call within the function
// thus nobody can provide one
};
int countRecursive(int cancelCondition, std::unique_ptr<Counter> c)
{
if (c == nullptr)
c = std::unique_ptr<Counter>(new Counter());
if(cancelCondition > 0)
{
c->count++;
return countRecursive(--cancelCondition, std::move(c));
}
else
{
return c->count;
}
}
int main() {
return countRecursive(12);
}
You can encapsulate the counter:
struct counterRecParam {
counterRecParam(int c) : cancelCondition(c),counter(0) {}
private:
int cancelCondition;
int counter;
friend int countRecursive(counterRecParam);
};
Now the caller cannot modify the counter, and you only need to modify the function slightly:
int countRecursive(counterRecParam crp)
{
if(crp.cancelCondition > 0)
{
--crp.cancelCondition;
++crp.counter;
return countRecursive(crp);
}
else
{
return crp.counter;
}
}
And the implicit conversion lets you call it with an int
counterRecursive(5);
One way to do this is to use a functor. Here's a simple example:
#include <iostream>
class counter
{
public:
unsigned operator()(unsigned m, unsigned n)
{
// increment the count on every iteration
++count;
// rest of the function
if (m == 0)
{
return n + 1;
}
if (n == 0)
{
return operator()(m - 1, 1);
}
return operator()(m - 1, operator()(m, n - 1));
}
std::size_t get_count() const
{
return count;
}
private:
// call count
std::size_t count = 0;
};
int main()
{
auto f = counter();
auto res = f(4, 0);
std::cout << "Result: " << res << "\nNumber of calls: " << f.get_count() << std::endl;
return 0;
}
Output:
Result: 13
Number of calls: 107
Since the count is stored in the object itself, the user cannot overwrite it.
Have you tried using "static" counter variable. Static variables gets initialized just once, and are best candidates to be used as counter variables.

Updating a pointer value with an integer during a recursive call in postorder traversal of a BST

int MovieTree::countMovieNodes()
{
int count = 0;
int* c = &count;
countMovieNodes(root,c);
return *c;
}
void MovieTree::countMovieNodes(MovieNode *node, int *c)
{
int count;
if(node == NULL)
{
return;
}
else
{
count ++;
countMovieNodes(node->leftChild, c);
countMovieNodes(node->rightChild, c);
}
}
My code is returning 0, so clearly I am misunderstanding the methodology to updating the pointer values. How do I fix this? I don't think my logic for post order traversal of the BST is the issue.
If you want to keep your current format, creating a new count is still making of copy of it, just incerment the pointer directly:
int MovieTree::countMovieNodes()
{
int count = 0;
int* c = &count;
countMovieNodes(root,c);
return *c;
}
void MovieTree::countMovieNodes(MovieNode *node, int *c)
{
if(node == NULL)
{
return;
}
else
{
++*c;
countMovieNodes(node->leftChild, c);
countMovieNodes(node->rightChild, c);
}
}
Your code doesn't actually use the c parameter (it just passes it on to recursive calls, which also don't use c). Your code also creates a local count variable in each call, which is only incremented (not written to or read from).
What you should do instead is
delete int count;
change count ++; to (*c)++; (or *c += 1; if you don't like parens) to increment the count variable in the top-level countMovieNodes() call)

How do I return value to main function without directly calling the function

I have multiple functions in my program. Each function has some conditions. If conditions are met, then it passes on the value to another function which again checks the value with some conditions, modifies it.
The first function [named 'squarefree()'] is called from main [obviously] and it further goes on to call another function which in course calls another function untill the process stops at last function named 'end()'. Like this:
#include <iostream>
using namespace std;
int squarefree(int n);
int goodnumber(int sf);
int end(int gn);
int main() {
// your code goes here
int l,r;
cin>>l;
cin>>r;
for(int p=l;p<=r;p++)
{squarefree(p);}
/*int ret=end(int gn); PROBLEM LIES HERE
cout<<ret; */
return 0;
}
int squarefree(int n){
int i;
for(int i=2;i<n;i++)
{
if((n%(i*i))==0)
{
cout<<"number not square free"<<endl;
break;
}
else{
cout<<"number square free"<<endl;
goodnumber(n);
break;
}
}
return 0;
}
int goodnumber(int sf){
cout<<"Sf is:"<<sf<<endl;
int s=0,c=0,flag=0;
for(int j=1;j<=sf;j++)
{
if(sf%j==0)
{
s+=j;
for(int k=2;k<=j/2;++k)
{
if(j%k==0)
{
c++;
}
}
}
}
cout<<"s is:"<<s<<endl;
cout<<"no.of prime numbers dividin s are:"<<c<<endl;
for(int l=2;l<=c/2;++l)
{
if(c%l==0)
{
flag=1;
break;
}
}
if (flag==0)
{cout << "C is a prime number, so this is good number and needs to be passed to next function"<<endl;
end(s);
}
else
{cout << "C is not a prime number"<<endl;
}
return 0;
}
int end(int gn)
{
int sum=0;
sum+=gn;
cout<<"SUm of factors of the good number is:"<<sum<<endl;
return sum;
}
The 'end()' function returns a value sum. Now I want this value sum to be updated everytime the for loop in main() function runs. For example: Sum in first iterations is 5, sum is 2nd iteration is 10, so total sum gets 15 and so on.
If somehow, the value returned by end function can be fetched into main function, that would be great.
Look at all those int-returning functions that are always returning 0. You might be able to take advantage of that.
A trivial example:
#include <iostream>
int step3(int val)
{
return val * val;
}
int step2(int val)
{
return step3(val + 1);
}
int step1(int val)
{
return step2(val * 2);
}
int main()
{
std::cout << step1(1);
}
But take care. You might find a case where you don't get any valid results and need to inform the caller that no result was found.
In addition to the idea of having the functions return the result of the next stage in the pipeline, which is an excellent idea, you can pass the address of the variable in which to store the result (allowing you to return more than one result, or an error code), or store the result of each stage in a temporary variable and return that (allowing you to use a result in more than one computation). I would advise against using a global variable to bypass the stack; it’s considered poor practice.
Some Examples:
// Returning the result of the next stage in the pipeline:
int g(int);
int f(int x)
{
return g(x);
}
// Passing a variable by reference:
enum errcode { success, failure };
errcode sqr( int input, int& output )
{
output = input * input; // This modifies the second variable the caller gave.
return success;
}
// Storing in a temporary variable:
int stage2(int);
int stage1(int x)
{
const int y = stage2(x); // Store the result in a temporary.
const int z = sqr(y);
return z;
}
// Passing results through a global variable is a bad idea:
int necessary_evil = 0; // Declared in global scope; should at least be
// declared static if possible to make it visible only in this source file.
// Namespaces are a fancier way to do something similar.
void kludge(int x)
{
necessary_evil = x * x; // The caller will check the global.
return;
}
There are examples of all of these in the standard library: printf() is essentially a wrapper for vfprintf(), strtol() takes a parameter by reference that the function sets to a pointer to the remainder of the string, and errno is a global variable.

How to reset a static vector inside a function?

I am trying to solve a certain problem on an online judge using the Dynamic Programming paradigm. I have written a function which memoizes the results of smaller subproblems. But this function will be called t times in a single run. So when the function calls itself I want its "Memory" to be preserved, but when it is called from the driver I wan't the vector to be reset. How do I do that? I think having a global vector and reseting it after each call from the driver is possible, but as I have learnt from books and stack overflow that is "bad programming style". So what is a good sollution to this problem? Heres the code :
class mem{
public:
bool mike_win;
bool written;
};
bool calc(int a){
static vector<mem> memory(a);
if( a == 1){
return false;
}
if(memory[a-1].written == true){
return (!(memory[a-1].mike_win))
}
vector<int> div_list = divis(a);
//^^ divis is a function which takes a number and returns
//all its divisors in descending order in a vector<int>
for(vector<int>::iterator i = div_list.begin();i != div_list.end();i++){
if ( ! ( calc( a / (*i) ))){
memory[a-1].written = true;
memory[a-1].mike_win = true;
return true;
}
}
if(calc(a-1 ) == false){
memory[a-1].written = true;
memory[a-1].mike_win = true;
return true;
}
else{
memory[a-1].written = false;
memory[a-1].mike_win = false;
return false;
}
}
Heres a link to the question. And heres the function divis :
vector<int> divis(int a){
vector<int> div_list(int a )
if(a==2){
return div_list;
}
int k = sqrt(a);
for(int i=2;i<=k;i++){
if(!(a%i)){
div_list.push_back(i);
div_list.push_back(a/i);
}
}
sort(div_list.rbegin(),div_list.rend());
div_list.erase(unique(div_list.begin(),div_list.end()),div_list.end());
return div_list;
}
I think the way I would do it is to create two overloads of calc: on that takes just int as a parameter, and another that takes an int and a reference to vector<int>. That way, a user will call the first overload, which will create the temporary vector for memorization, and pass it to the second function, which passes the reference upon recursion. Kinda like this:
bool calc(int a, vector<int>& memory)
{
// Do your stuff here
// Instead of calling it as calc( a / (*i) ), just call
// it as calc( a / (*i) , memory )
}
bool calc(int a)
{
vector<int> memory(a);
calc(a, memory);
}
That way, you avoid having to do any sort of book-keeping in the heart of your algorithm to determine whether to clear the vector or not; it will be done automatically after the first call returns.

Ternary Search Tree

struct Ternary {
char current;
bool wordend;
Ternary* left;
Ternary* mid;
Ternary* right;
Ternary(char c='#',Ternary* l=NULL, Ternary* m=NULL, Ternary* r=NULL,bool end=false)
{
wordend=end;
current=c;
left=l;
mid=m;
right=r;
}
};
void add(Ternary* t, string s, int i) {
if (t == NULL) {
Ternary* temp = new Ternary(s[i],NULL,NULL,NULL,false);
t=temp;
}
if (s[i] < t->current) {
add(t->left,s,i);
}
else if (s[i] > t->current) {
add(t->right,s,i);
}
else
{
if ( i + 1 == s.length()) {
t->wordend = true;
}
else
{
add(t->mid,s,i+1);
}
}
}
When I add sequence of words using add() the string are getting printed inside
if(t==NULL) segment but tree isn't getting formed i.e nodes are not getting linked.
t=temp;
This line has no effect outside of the add() function. The caller's pointer is not updated.
You could change your function to return a Ternary* (return t in this case at the end of it), and change the call sites to:
Ternary *tree = 0;
tree = add(tree, "hello", 1);
tree = add(tree, "bye", 1);
...
Just a little trick will do:
Replace:
void add(Ternary* t, string s, int i)
With:
void add(Ternary*& t, string s, int i)
That's cleaner than passing and then reading output like this:
tree = add(tree, "bye", 1);
When in C++, make use of their references :) In C you would change the function signature to:
void add(Ternary** t, string s, int i)
and remember to correct t in relevant places.
Well, C++ is clearly cleaner :)