Data structures: how do I draw recursion trees? - java

I have a question which I'm not sure how to begin. Can someone explain how to do this recursion tree? And is there anyway to do it on Java?
For the recursive method fnc(n,k) defined below, draw the recursion tree of the call fnc(3,5).
Your diagram should include the return values for all calls to method
fnc(n,k).
public static int fnc(int n, int k) {
if ( (n <= 1) || (k <= 1) ) {
return n+k; } else {
return fnc(n-1,k) + fnc(n,k-2);
}
}

If I understand correctly, you just need to keep track of the level at which the recursion is and use that to control the indenting...
Single entry single exit would probably help here so only need one print statement for the return
String.format() quite handy for output multiple values
pad() method to create repeated string - see Simple way to repeat a String in java for alternatives
Example
static int fnc(int n, int k, int level) {
System.out.println(String.format("%sfnc(%d, %d)", pad(level), n, k));
int result;
if ((n <= 1) || (k <= 1)) {
result = n + k;
} else {
result = fnc(n - 1, k, level + 1) + fnc(n, k - 2, level + 1);
}
System.out.println(String.format("%s<== %d", pad(level), result));
return result;
}
private static String pad(int level) {
String pad = "";
for (int i = 0; i < level; i++) {
pad += " ";
}
return pad;
}
public static void main(String[] args) {
fnc(3, 5, 0);
}
Output
fnc(3, 5)
fnc(2, 5)
fnc(1, 5)
<== 6
fnc(2, 3)
fnc(1, 3)
<== 4
fnc(2, 1)
<== 3
<== 7
<== 13
fnc(3, 3)
fnc(2, 3)
fnc(1, 3)
<== 4
fnc(2, 1)
<== 3
<== 7
fnc(3, 1)
<== 4
<== 11
<== 24

Related

Multiplying values in array if same [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I wanna write a recursive method that follows this logic:
suppose if the array is [3, 3, 3, 3] it will return a value of 30 because the consecutive number for trail[i] are equal to each other. So what happens here is 3 + (3 * 2) + (3 * 3) + (3 * 4) = 30
Another example is [2, 4, 3] it will return a value of 9
I hope this makes sense
Can anyone help?
Why do you need recursion for this?
Simple loop should do the job:
public int sum(int[] arr) {
int sum = 0;
for (int i = 0, p = 0; i < arr.length; i++) {
if (i == 0 || arr[i] == arr[i - 1]) {
p++;
} else {
p = 1;
}
sum += arr[i] * p;
}
return sum;
}
update
Java 8 Stream API may be used to produce the same result:
public int sumStream(int[] arr) {
int[] pp = {0};
return IntStream.range(0, arr.length)
// update the quotient for the i-th element
.peek(i -> {
pp[0] = i == 0 || arr[i] == arr[i - 1] ? pp[0] + 1 : 1;
})
.map(i -> pp[0] * arr[i])
.sum();
}
You can try this way
int sum(int pos, int[] trail, int cnt) {
if (pos >= trail.length) { // when full array traversed
return 0;
}
if (pos != 0 && trail[pos - 1] == trail[pos]) { // if previous element is same
return (cnt + 1) * trail[pos] + sum(pos + 1, trail, cnt + 1);
} else { // first element or prev not same
return trail[pos] + sum(pos + 1, trail, 1);
}
}
And call this way sum(0, trail, 0)
As others already mentioned that this could be easily written as an interative function without using recursion but if for some reason you still want a recursive function then it will be something like below:
int recursiveHelper(int[] nums, int index, int pow){
if(index >= nums.length) return 0;
if(index == 0)
return nums[0] + recursiveHelper(nums, index+1,0);
else{
if(nums[index] == nums[index-1])
return nums[index] * pow + recursiveHelper(nums, index, pow+1);
else
return nums[index] + recursiveHelper(nums, index+1,0);
}
}
Notice how we pass the pow variable to track the repetition of integers. If a number is not equal to its previous number, we ignore pow and set it 0. If it is equal to previous number, we increment pow and call the recursive function.
Note : I didn't execute this, there may be some typos and errors here but this should give you an idea on how to start.
int[] values = new int[]{3,3,3,3};
int currentNumber=0,previousNumber=-1,count=1,sum=0;
for(int i = 0; i<values.length;i++,previousNumber = currentNumber){
currentNumber = values[i];
if(currentNumber == previousNumber){
count++;
}else{
count=1;
}
sum += currentNumber*count;
}
System.out.println("Sum : " + sum);

Is this Recursion computing the powers of 2 from 1 to n us correct?

First call of int prev = powersOf2(n / 2) should got to else block where it
will be shown as 50 but compiler showing below
Is this Recursion computing the powers of 2 from 1 through n correct?
package Example_16;
public class Example {
public static int powersOf2(int n) {
if (n < 1) {
return 0;
} else if (n == 1) {
System.out.println(1);
return 1;
} else {
int prev = powersOf2(n / 2);
int curr = prev * 2;
System.out.println(curr);
return curr;
}
}
public static void main(String[] args) {
powersOf2(50);
}
}
First call of int prev = powersOf2(n / 2) should got to else block where it
will be shown as 50 but compiler showing below
1
2
4
8
16
32
But output is printed as ,but how its returning 8 16 and 32
print & return 1
print & return 2
print & return 4
print & return 8
print & return 16
print & return 32

Fibonacci Modified:How to fix this algorithm?

I have this problem in front of me and I can't figure out how to solve it.
It's about the series 0,1,1,2,5,29,866... (Every number besides the first two is the sum of the squares of the previous two numbers (2^2+5^2=29)).
In the first part I had to write an algorithm (Not a native speaker so I don't really know the terminology) that would receive a place in the series and return it's value (6 returned 29)
This is how I wrote it:
public static int mod(int n)
{
if (n==1)
return 0;
if (n==2)
return 1;
else
return (int)(Math.pow(mod(n-1), 2))+(int)(Math.pow(mod(n-2), 2));
}
However, now I need that the algorithm will receive a number and return the total sum up to it in the series (6- 29+5+2+1+1+0=38)
I have no idea how to do this, I am trying but I am really unable to understand recursion so far, even if I wrote something right, how can I check it to be sure? And how generally to reach the right algorithm?
Using any extra parameters is forbidden.
Thanks in advance!
We want:
mod(1) = 0
mod(2) = 0+1
mod(3) = 0+1+1
mod(4) = 0+1+1+2
mod(5) = 0+1+1+2+5
mod(6) = 0+1+1+2+5+29
and we know that each term is defined as something like:
2^2+5^2=29
So to work out mod(7) we need to add the next term in the sequence x to mod(6).
Now we can work out the term using mod:
x = term(5)^2 + term(6)^2
term(5) = mod(5) - mod(4)
term(6) = mod(6) - mod(5)
x = (mod(5)-mod(4))^2 + (mod(6)-mod(5))^2
So we can work out mod(7) by evaluating mod(4),mod(5),mod(6) and combining the results.
Of course, this is going to be incredibly inefficient unless you memoize the function!
Example Python code:
def f(n):
if n<=0:
return 0
if n==1:
return 1
a=f(n-1)
b=f(n-2)
c=f(n-3)
return a+(a-b)**2+(b-c)**2
for n in range(10):
print f(n)
prints:
0
1
2
4
9
38
904
751701
563697636866
317754178345850590849300
How about this? :)
class Main {
public static void main(String[] args) {
final int N = 6; // Your number here.
System.out.println(result(N));
}
private static long result(final int n) {
if (n == 0) {
return 0;
} else {
return element(n) + result(n - 1);
}
}
private static long element(final int n) {
if (n == 1) {
return 0L;
} else if (n == 2) {
return 1L;
} else {
return sqr(element(n - 2)) + sqr(element(n - 1));
}
}
private static long sqr(final long x) {
return x * x;
}
}
Here is the idea that separate function (element) is responsible for finding n-th element in the sequence, and result is responsible for summing them up. Most probably there is a more efficient solution though. However, there is only one parameter.
I can think of a way of doing this with the constraints in your comments but it's a total hack. You need one method to do two things: find the current value and add previous values. One option is to use negative numbers to flag one of those function:
int f(int n) {
if (n > 0)
return f(-n) + f(n-1);
else if (n > -2)
return 0;
else if (n == -2)
return 1;
else
return f(n+1)*f(n+1)+f(n+2)*f(n+2);
}
The first 8 numbers output (before overflow) are:
0
1
2
4
9
38
904
751701
I don't recommend this solution but it does meet your constraints of being a single recursive method with a single argument.
Here is my proposal.
We know that:
f(n) = 0; n < 2
f(n) = 1; 2 >= n <= 3
f(n) = f(n-1)^2 + f(n-2)^2; n>3
So:
f(0)= 0
f(1)= 0
f(2)= f(1) + f(0) = 1
f(3)= f(2) + f(1) = 1
f(4)= f(3) + f(2) = 2
f(5)= f(4) + f(3) = 5
and so on
According with this behaivor we must implement a recursive function to return:
Total = sum f(n); n= 0:k; where k>0
I read you can use a static method but not use more than one parameter into the function. So, i used a static variable with the static method, just for control the execution of loop:
class Dummy
{
public static void main (String[] args) throws InterruptedException {
int n=10;
for(int i=1; i<=n; i++)
{
System.out.println("--------------------------");
System.out.println("Total for n:" + i +" = " + Dummy.f(i));
}
}
private static int counter = 0;
public static long f(int n)
{
counter++;
if(counter == 1)
{
long total = 0;
while(n>=0)
{
total += f(n);
n--;
}
counter--;
return total;
}
long result = 0;
long n1=0,n2=0;
if(n >= 2 && n <=3)
result++; //Increase 1
else if(n>3)
{
n1 = f(n-1);
n2 = f(n-2);
result = n1*n1 + n2*n2;
}
counter--;
return result;
}
}
the output:
--------------------------
Total for n:1 = 0
--------------------------
Total for n:2 = 1
--------------------------
Total for n:3 = 2
--------------------------
Total for n:4 = 4
--------------------------
Total for n:5 = 9
--------------------------
Total for n:6 = 38
--------------------------
Total for n:7 = 904
--------------------------
Total for n:8 = 751701
--------------------------
Total for n:9 = 563697636866
--------------------------
Total for n:10 = 9011676203564263700
I hope it helps you.
UPDATE: Here is another version without a static method and has the same output:
class Dummy
{
public static void main (String[] args) throws InterruptedException {
Dummy app = new Dummy();
int n=10;
for(int i=1; i<=n; i++)
{
System.out.println("--------------------------");
System.out.println("Total for n:" + i +" = " + app.mod(i));
}
}
private static int counter = 0;
public long mod(int n)
{
Dummy.counter++;
if(counter == 1)
{
long total = 0;
while(n>=0)
{
total += mod(n);
n--;
}
Dummy.counter--;
return total;
}
long result = 0;
long n1=0,n2=0;
if(n >= 2 && n <=3)
result++; //Increase 1
else if(n>3)
{
n1 = mod(n-1);
n2 = mod(n-2);
result = n1*n1 + n2*n2;
}
Dummy.counter--;
return result;
}
}
Non-recursive|Memoized
You should not use recursion since it will not be good in performance.
Use memoization instead.
def FibonacciModified(n):
fib = [0]*n
fib[0],fib[1]=0,1
for idx in range(2,n):
fib[idx] = fib[idx-1]**2 + fib[idx-2]**2
return fib
if __name__ == '__main__':
fib = FibonacciModified(8)
for x in fib:
print x
Output:
0
1
1
2
5
29
866
750797
The above will calculate every number in the series once[not more than that].
While in recursion an element in the series will be calculated multiple times irrespective of the fact that the number was calculated before.
http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/

All combinations of 1 + 2 that adds to n

I am trying to solve this question as the preparation for a programming interview:
A frog only moves forward, but it can move in steps 1 inch long or in jumps 2 inches long. A frog can cover the same distance using different combinations of steps and jumps.
Write a function that calculates the number of different combinations a frog can use to cover a given distance.
For example, a distance of 3 inches can be covered in three ways: step-step-step, step-jump, and jump-step.
I think there is a quite simple solution to this, but I just can't seem to find it. I would like to use recursion, but I can't see how. Here is what I have so far:
public class Frog {
static int combinations = 0;
static int step = 1;
static int jump = 2;
static int[] arr = {step, jump};
public static int numberOfWays(int n) {
for (int i = 0; i < arr.length; i++) {
int sum = 0;
sum += arr[i];
System.out.println("SUM outer loop: " + sum + " : " + arr[i]);
while (sum != 3) {
for (int j = 0; j < arr.length; j++) {
if (sum + arr[j] <= 3) {
sum += arr[j];
System.out.println("SUM inner loop: " + sum + " : " + arr[j]);
if (sum == 3) {
combinations++;
System.out.println("Combinations " + combinations);
}
}
}
}
}
return combinations;
}
public static void main(String[] args) {
System.out.println(numberOfWays(3));
}
}
It doesn't find all combinations, and I think the code is quite bad. Anyone have a good solution to this question?
Think you have an oracle that knows how to solve the problem for "smaller problems", you just need to feed it with smaller problems. This is the recursive method.
In your case, you solve foo(n), by splitting the possible moves the frog can do in the last step, and summing them):
foo(n) = foo(n-1) + foo(n-2)
^ ^
1 step 2 steps
In addition, you need a stop clause of foo(0) = 1, foo(1)=1 (one way to move 0 or 1 inches).
Is this recursive formula looks familiar? Can you solve it better than the naive recursive solution?
Spoiler:
Fibonacci Sequence
Here's a simple pseudo-code implementation that should work:
var results = []
function plan(previous, n){
if (n==0) {
results.push(previous)
} else if (n > 0){
plan(previous + ' step', n-1)
plan(previous + ' hop', n-2)
}
}
plan('', 5)
If you want to improve the efficiency of an algorithm like this you could look into using memoization
Here's a combinatoric way: think of n as 1 + 1 + 1 ... = n. Now bunch the 1's in pairs, gradually increasing the number of bunched 1's, summing the possibilities to arrange them.
For example, consider 5 as 1 1 1 1 1:
one bunch => (1) (1) (1) (11) => 4 choose 1 possibilities to arrange one 2 with three 1's
two bunches => (1) (11) (11) => 3 choose 2 possibilities to arrange two 2's with one 1
etc.
This seems directly related to Wikipedia's description of Fibonacci numbers' "Use in Mathematics," for example, in counting "the number of compositions of 1s and 2s that sum to a given total n" (http://en.wikipedia.org/wiki/Fibonacci_number).
This logic is working fine. (Recursion)
public static int numberOfWays(int n) {
if (n== 1) {
return 1; // step
} else if (n== 2) {
return 2; // (step + step) or jump
} else {
return numberOfWays(n- 1)
+ numberOfWays(n- 2);
}
}
The accepted answer fails performance test for larger sets. Here is a version with for loop that satisfies performance tests at testdome.
using System;
public class Frog
{
public static int NumberOfWays (int n)
{
int first = 0, second = 1;
for ( int i = 0; i<n; i++ )
{
int at = first;
first = second;
second = at + second;
}
return second;
}
public static void Main (String[] args)
{
Console.WriteLine (NumberOfWays (3));
}
}
C++ code works fine.
static int numberOfWays(int n)
{
if (n == 1) return 1;
else if (n == 2) return 2;
else
{
static std::unordered_map<int,int> m;
auto i = m.find(n);
if (i != m.end())
return i->second;
int x = numberOfWays(n - 1) + numberOfWays(n - 2);
m[n] = x;
return x;
}
}

Count All Permutations Where No Two Adjacent Characters Are the Same

Given a sequence which contains only various amounts of the numbers 1, 2, 3, and 4 (examples: 13244, 4442, etc), I want to count all its permutations such that no two adjacent numbers are the same. I believe it is O(N! * N) and want to know if there is a better one out there. Anyone have any ideas?
class Ideone
{
static int permutationCount++;
public static void main(String[] args) {
String str = "442213";
permutation("", str);
System.out.println(permutationCount);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0){
boolean bad = false;
//Check whether there are repeating adjacent characters
for(int i = 0; i < prefix.length()-1; i++){
if(prefix.charAt(i)==prefix.charAt(i+1))
bad = true;
}
if(!bad){
permutationCount++;
}
}
else {
//Recurse through permutations
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
}
I understand your question like this: Given a string containing only numbers 1,2,3,4 - how many permutations of these characters exist that when you put them into string again there won't be any same adjecent numbers.
I would suggest this approach:
L - length of your string
n1 - how many times is 1 repeated, n2 - how many times is 2 repeated etc.
P - number of all possible permutations
P = L! / (n1!*n2!*n3!*n4!)
C - number of all solutions fitting your constraint
C = P - start with all permutations
substract all permutations which have 11 in it (just take 11 as one number)
C = C - (L - 1)! / ((n1 - 1)! * n2! * n3! * n4!)
... do the same for 22 ...
add all permutations which have both 11 and 22 in it (because we have substracted them twice, so you need to add them)
C = C + (L - 2)! / ((n1 - 1)! * (n2 - 1)! * n3! * n4!)
... repeat previous steps for 33 and 44 ...
If you just want to calculate how many permutations match your constraint, it is not required to spell each of them out.
If I get your question right, your input string has 4 distinct input characters 1,2,3,4 and you want to know how many permutations of this are possible?
Then you should use some maths, namely n! / (n-r)!, where n is the number of elements to choose from (4 in this case) and r is the number of positions you want to fill (also 4).
Your example would have 4! / (4-4)! = 24 permutations possible:
{1,2,3,4} {1,2,4,3} {1,3,2,4} {1,3,4,2} {1,4,2,3} {1,4,3,2}
{2,1,3,4} {2,1,4,3} {2,3,1,4} {2,3,4,1} {2,4,1,3} {2,4,3,1}
{3,1,2,4} {3,1,4,2} {3,2,1,4} {3,2,4,1} {3,4,1,2} {3,4,2,1}
{4,1,2,3} {4,1,3,2} {4,2,1,3} {4,2,3,1} {4,3,1,2} {4,3,2,1}
In a nutshell, for length n with n distinct values the count of permutations is n!:
1 -> 1
2 -> 2
3 -> 6
4 -> 24
5 -> 120
...
Edit: After your edits and comments it is clear that I misunderstood the question.
If you just want to check to see if there are no matching adjacent numbers, then you can use a simple loop. This will be O(n) complexity.
public static void main(String[] args) {
String str = "442213";
System.out.println(permutation(str));
}
public static int permutation(String str) {
int permutationCount = 0;
if (str.length() > 1) {
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) != str.charAt(i + 1)) {
permutationCount++;
}
}
}
return permutationCount;
}
If you wanted to stick with recursion, you could do something like this:
public static void main(String[] args) {
String str = "442213";
System.out.println(permutation(str, 0));
}
public static int permutation(String str, int currentIndex) {
int permutationCount = 0;
if (str == null || currentIndex + 1 >= str.length()) {
return permutationCount;
}
if (str.charAt(currentIndex) != str.charAt(currentIndex + 1)) {
permutationCount = 1;
}
return permutationCount + permutation(str, currentIndex + 1);
}

Categories