Calculating a value to return using recursion - recursion

In this recursive method, I am trying to calculate a number using the initial call mystery5(-23, -48). After going through my first series of if statements, I get to the numbers 23 and 48. Once I get to the else branch of the decision statements, what precedence does the method call have in the equation? Also, does a negative sign in front of the mystery5 method call in the first two if statements indicate that there will be a positive x value if -23 is inserted into the method call (Ex: -mystery5(-23, -48))?
public int mystery5(int x, int y){
if (x < 0) {
return -mystery5(-x, y);
} else if (y < 0) {
return -mystery5(x, -y);
} else if (x == 0 && y == 0) {
return 0;
} else {
return 100 * mystery5(x / 10, y / 10) + 10 * (x % 10) + y % 10;
}
}

So it looks to me that mystery5(1, 0) returns 1. Assuming that is correct, then the call mystery5(-1, 0) would hit that first statement and it would see that x = -1) which is less than zero. This does return -mystery5(-x,y), so when the values for x and y are put in, this is equivalent to return -mystery5(1,0). The - in front of mystery5 flips the sign on the result of the mystery5 function when called. So when mystery5(1,0) returns a 1, that gets negated to -1. And that is the final return value of mystery5(-1,0).

Related

FINDING total number of paths using backtracking

I'm trying to count total paths in a 20x20 grid(ProjectEuler #15) using backtracking.I've played around with it but the answer is always None. Any help would be appreciated(I know it can be solved using recursion or memoization but i want to solve it using backtracking)
def isvalid(maze,n,x,y):
if x<0 or y<0 or x>n or y>n :
return False
else: return True
def countPaths(maze,x,y,n,used,count):
if x==n-1 or y==n-1:
count+=1
return
if isvalid(maze,n,x,y):
used[x][y]=True
if (x+1<n and used[x+1][y]==False):
countPaths(maze,x+1,y,n,used,count)
if (x-1>0 and used[x-1][y]==False):
countPaths(maze,x-1,y,n,used,count)
if (y+1<n and used[x][y+1]==False):
countPaths(maze,x,y+1,n,used,count)
if (y-1>0 and used[x][y-1]==False):
countPaths(maze,x,y-1,n,used,count)
used[x][y]=False
return
Since in the base case, you are only returning 1 whenever end of row or column occurs it would yield wrong answer.
You should increment a counter signifying the number of times you are able to reach the final [n-1][n-1] i.e rightmost bottom cell.
bool isValid(int x, int y)
{
if (x < 0 || x >= n || y < 0 || y >= n)
return false;
return true;
}
void countPaths(int x, int y)
{
// cout << x << y << endl;
if (x == n - 1 && y == n - 1)
{
paths++;
return;
}
if (isValid(x, y))
{
visited[x][y] = true;
countPaths(x, y + 1);
countPaths(x + 1, y);
}
return;
}
Keeping paths & visited as global variables , I implemented the above approach.
For n=2 (1+1): 2
For n=3 (2+1): 6
For n=4 (3+1): 20
For n=5 (4+1): 70
however, this approach would not be viable for n=20.
I would suggest trying Dynamic Programming as it would simplify the process!

Counting the number

I have got a code that generates all possible correct strings of balanced brackets. So if the input is n = 4 there should be 4 brackets in the string and thus the answers the code will give are: {}{} and
{{}}.
Now, what I would like to do is print the number of possible strings. For example, for n = 4 the outcome would be 2.
Given my code, is this possible and how would I make that happen?
Just introduce a counter.
// Change prototype to return the counter
int findBalanced(int p,int n,int o,int c)
{
static char str[100];
// The counter
static int count = 0;
if (c == n) {
// Increment it on every printout
count ++;
printf("%s\n", str);
// Just return zero. This is not used anyway and will give
// Correct result for n=0
return 0;
} else {
if (o > c) {
str[p] = ')';
findBalanced(p + 1, n, o, c + 1);
}
if (o < n) {
str[p] = '(';
findBalanced(p + 1, n, o + 1, c);
}
}
// Return it
return count;
}
What you're looking for is the n-th Catalan number. You'll need to implement binomial coefficient to calculate it, but that's pretty much it.

2 things that I am confused about tail recursion

I've several confusion about tail recursion as follows:
some of the recursion functions are void functions for example,
// Prints the given number of stars on the console.
// Assumes n >= 1.
void printStars(int n) {
if (n == 1) {
// n == 1, base case
cout << "*";
} else {
// n > 1, recursive case
cout << "*"; // print one star myself
printStars(n - 1); // recursion to do the rest
}
}
and another example:
// Prints the given integer's binary representation.
// Precondition: n >= 0
void printBinary(int n) {
if (n < 2) {
// base case; same as base 10
cout << n;
} else {
// recursive case; break number apart
printBinary(n / 2);
printBinary(n % 2);
}
}
As we know by definition tail recursion should return some value from tail call. But for void functions it does not return any value. By intinction I think they are tail recursion but I am not confident about it.
another question is that, if a recursion function has several logical end, should tail recursion come at all logical ends or just one of the logical ends? I saw someone argued that only one of the logical ends is OK, but I am not sure about that. Here's my example:
// Returns base ^ exp.
// Precondition: exp >= 0
int power(int base, int exp) {
if (exp < 0) {
throw "illegal negative exponent";
} else if (exp == 0) {
// base case; any number to 0th power is 1
return 1;
} else if (exp % 2 == 0) {
// recursive case 1: x^y = (x^2)^(y/2)
return power(base * base, exp / 2);
} else {
// recursive case 2: x^y = x * x^(y-1)
return base * power(base, exp - 1);
}
}
Here we have logical end as tail recursion and another one that is not tail recursion. Do you think this function is tail recursion or not? why?

How to calculate factorial of a factorial recursively?

I have encountered the following problem:
N is positive non-zero integer and I have to calculate the product of : N*(N-1)^2*(N-2)^3*..*1^N.
My solution so far is as follows:
N*myFact(N-1)*fact(N-1)
The thing is I'm not allowed to use any helping functions, such as 'fact()'.
EDIT: Mathematically it can be represented as follows: N!*(N-1)! (N-2)!..*1!
This function is called the superfactorial. A recursive implementation is
long superFact(n) {
if (n < 2) return 1;
long last = superFact(n-1);
long prev = superFact(n-2);
return last * last / prev * n;
}
but this is very inefficient -- it takes about 3*F(n) recursive calls to find superFact(n), where F(n) is the n-th Fibonacci number. (The work grows exponentially.)
Try:
int myFact(int n) {
return n == 1 ? 1 : myFact(n-1)*n;
}
I assume this needs to be accomplished with 1 function i.e. you're not allowed to create a fact helper function yourself.
You can use the fact that myFact(n-1) / myFact(n-2) == (n-1)!
int myFact(int n)
{
if (n == 0 || n == 1) {
return 1
} else {
// (n - 1)!
int previousFact = myFact(n - 1) / myFact(n - 2);
return myFact(n - 1) * previousFact * n;
}
}

Binary math

If I know the number number y and know that 2^x=y, how do I compute x?
Base 2 logarithm function:
log2(y)
which is equivalent to:
log(y) / log(2)
for arbitrary base.
And in case you don't have a log function handy, you can always see how many times you must divide y by 2 before it becomes 1. (This assumes x is positive and an integer.)
If you are sure that it is a power of 2, then you can write a loop and right shift the number until you get a 1. The number of times the loop ran will be the value of x.
Example code:
int power(int num)
{
if(0 == num)
{
return 0;
}
int count = 0;
do
{
++count;
num = num >> 1;
}while(! (num & 1) && num > 0);
return count;
}
If x is a positive integer, then, following code will be more efficient..
unsigned int y; // You know the number y for which you require x..
unsigned int x = 0;
while (y >>= 1)
{
x++;
}
x is the answer!

Resources