I'm having trouble trying to figure out how to keep track of the amount of times my recursive function calls itself while performaing collatz function. I have the function definition:
template<class myType>
myType recursionSet<myType>::collatz(myType n)
{
if(n == 1)
return 1;
else {
if(n%2 == 1)
return collatz(3*n+1);
else
return collatz(n/2);
}
}
how can i keep track of the number of times this function calls itself? I cannot seem for the life of me to come up with a solution. Thanks!
reference to collatz function: http://www.xamuel.com/collatz-recursion/
You are trying to compute the length of the Collatz chain, aren't you. Do you realise that currently you always return 1? You should modify your code to return the count instead. That means adding the current iteration to the recursive call:
template<class myType>
myType recursionSet<myType>::collatz(myType n)
{
if(n == 1)
return 1;
else {
if(n%2 == 1)
return 1 + collatz(3*n+1);
else
return 1 + collatz(n/2);
}
}
Related
I've been trying to get a better understanding of recursive functions, and I was working on a problem trying to figure out why it wasn't working properly.
I want it to go through the array, and when it finds a 0, to return true.
But the function stills return true when there's no zero.
Here is my code:
bool containZero(int randomArray[], int length)
{
if(randomArray[length] == 0)
return true;
else
{
return containZero(randomArray, length - 1);
}
}
Your algorithm is not handling the possibility that the array may not actually contain a zero. You need to stop iterating when the end of the array is reached.
You are also accessing the array out of bounds from the very 1st iteration, and also if no zero is found.
Not only that, but there is no branch of your recursion logic that ever returns false. Your return statements are always returning true.
Try this instead:
// this searches backwards...
bool containZero(int randomArray[], int length)
{
if (length <= 0)
return false;
--length;
if (randomArray[length] == 0)
return true;
return containZero(randomArray, length);
}
Online Demo
Alternatively:
// this searches forwards...
bool containZero(int randomArray[], int length)
{
if (length <= 0)
return false;
if (randomArray[0] == 0)
return true;
return containZero(randomArray+1, length-1);
}
Online Demo
While learning recursion I tried to implement binary search.Both my functions provide the correct answer.Can someone explain why?
I feel that in the first function the recursive function return the values found to the previous functions but in the second function the recursive functions are just called and the call which hits the base case or which gets the answer returns directly to main().
Can someone please confirm if in the second case the function where the base case is reached or the element is found it's returned directly to main() and not to the previous recursive functions in the callstack, if there is one needed in the second case.
int bins1(int *arr,int l,int h,int el){
if(l>h){
return -1;
}
int mid = (l+h)/2;
if(arr[mid] == el){
return mid+1;
}
else if(arr[mid] > el){
return bins1(arr,mid+1,h,el);
}
else if(arr[mid] < el){
return bins1(arr,l,mid-1,el);
}
}
int bins2(int *arr,int l,int h,int el){
if(l>h){
return -1;
}
int mid = (l+h)/2;
if(arr[mid] == el){
return mid+1;
}
else if(arr[mid] > el){
bins2(arr,mid+1,h,el);
}
else if(arr[mid] < el){
bins2(arr,l,mid-1,el);
}
}
I am building a binary tree in C++ using recursion and I can't figure out why I can't return an Item, it's probably a simple thing I'm over looking but I've been looking at it so long I can't figure it out.
BST::Item * BST::lookup(Key k)
{
return(lookupRec(k, root));
}
BST::Item * BST::lookupRec(Key k, Node* n)
{
if (k == n->key)
{
return n->item; //problem is here
}
else if (k > n->key)
{
lookupRec(k, n->rightChild);
}
else if (k < n->key)
{
lookupRec(k, n->leftChild);
}
else
{
return nullptr;
}
}
to add some context Item is using Item = std::string; so I call the lookup with a key and it calls the worker function and should return the item when the key and root key match, but it won't return the n->item because it says there is no suitable conversion from BST::Item to BST::Item*
any help would be appreciated, thanks
Where you call lookupRec() recursively, you should also return, otherwise, you will return nothing from that function instance: return lookupRec(k, n->rightChild);
And as #UnholySheep already mentioned: return the right type, as the compiler tells you: return &(n->item);
I'm a little confused here. Let's look at the following code:
bool testing(int i) {
if((i%2)==0) {
return true;
} else {
--i;
testing(i);
}
return false;
}
When I do testing(5), I was expecting the function to return true because at some point, 5 will become 4, so 4 % 2 == 0, so the function will return true but it just wasn't the case. What's wrong?
You should return testing(i); instead of just testing(i);
The idea of recursion is when a function calls itself, directly or indirectly.
The function in your code will become recursive if it is modified to:
bool testing(int i){
// test if even, if so return true
if((i % 2) == 0){
return true;
// otherwise decrement and test again
}else{
// at this point the function calls itself with decremented argument
return testing(--i);
}
// I doubt that this case will be ever returned
// more likely your function will return "true" or run "forever" decrementing
return false;
}
To avoid infinite cycles you need a base case, termination condition that produces result without recursion. For example if i becomes very small or negative you return false.
bool testing(int i){
// base case
if(i < 0) return false;
// rest of the function
if((i % 2) == 0){
return true;
}else{
return testing(--i);
}
}
Making it a bit more concise, you finally have three cases:
bool testing(int i){
// base case
if(i < 0) return false;
// test if even
if((i % 2) == 0) return true;
// recursion step
return testing(--i);
}
For further reading, check this
You don't bubble up the final return value; you need to use return on the recursive call. Additionally, you can simplify the pre-decrement:
return testing(--i);
Because of you only call testing(i) function. That's why it's not call recursively.
you should write return testing(i)
it returns false because its return value is overridden by the last statement of "return false".
I have this challenging exercise I got from a book about c++, and i'm not sure how to tackle this problem.
I must define a function called treeNodeCount() which returns the number of nodes in a binary tree (easy enough), and I also have to define an overloaded function that takes an int(0,1, or 2) which represents the number of children, and the function should return the nodes that have that specific number of children.
treeNodeCount should both use a function called nodeCount(elemType root) to do the recursion necessary to count the nodes(so basically all the work).
challenge number one says that I can add a second parameter to nodeCount which takes the number of children for the nodes that we want to count.
Challenge number two says that we cannot use a second parameter (this is the tough part)
I was able to do challenge one and here is what I came up with:
template <class elemType>
int binaryTreeType<elemType>::nodeCount(nodeType<elemType> *p, int a ) const
{
if (p == NULL){
return 0;
}
else if (a == 0 && p->lLink == NULL && p->rLink == NULL){
return 1 + nodeCount(p->lLink, a) + nodeCount(p->rLink, a);
}
else if (a == 1 && (p->lLink != NULL ^ p->rLink != NULL)){
return 1 + nodeCount(p->lLink, a) + nodeCount(p->rLink, a);
}
else if (a == 2 && p->lLink != NULL && p->rLink != NULL){
return 1 + nodeCount(p->lLink, a) + nodeCount(p->rLink, a);
}
else if (a == -1){
return nodeCount(p->lLink, a) + nodeCount(p->rLink, a) + 1;
}
return nodeCount(p->lLink, a) + nodeCount(p->rLink, a);
}
template <class elemType>
int binaryTreeType<elemType>::treeNodeCount(int a) const{
return nodeCount(root, a);
}
This seems to work fine but i am convinced that there has to be a better way.
I was not able to do challenge 2 though, and i have no idea what to do (is it even possible)
You can scrunch down your logic and make it a bit more straightforward by implementing a function to return the number of children given a node.
template <class elemType>
int nodeSize(nodeType<elemType>* node) const
{
int count = 0;
if (node->lLink)
++count;
if (node->rLink)
++count;
return count;
}
template <class elemType>
int binaryTreeType<elemType>::nodeCount(nodeType<elemType>* node, int count) const
{
if (node)
{
if (nodeSize(node) == count || count == -1)
return nodeCount(node->lLink, count) + nodeCount(node->rLink, count) + 1;
return nodeCount(node->lLink, count) + nodeCount(node->rLink, count);
}
return 0;
}
For the second challenge, you need a stack to avoid recursion.
template <class elemType>
int binaryTreeType<elemType>::treeNodeCount(int count) const
{
stack<nodeType<elemType>*> node_stack;
node_stack.push(root);
int num_matches = 0;
while (!stack.empty())
{
nodeType<elemType>* node = node_stack.top();
node_stack.pop();
if (node)
{
if (nodeSize(node) == count || count == -1)
++num_matches;
node_stack.push(node->lLink);
node_stack.push(node->rLink);
}
}
return num_matches;
}
Edit: fixed a goof in the above recursive version. Thanks to David Rodriguez for pointing it out.