Recursive function not working as expected - java

I am trying to write the code for recursive function which prints every power of 2 from 1 to N, N is the argument of power function.
Function : int powers(n)
Currently I wrote this code:
int powers(int n) //here n=128
{
if(n==2)
{
System.out.print(n);
}
else if (n>2)
{
System.out.print(n +", ");
return powers(n/2);
}
System.out.println("");
return 0;
}
Output : 128, 64, 32, 16, 8, 4, 2
Expected : 2, 4, 8, 16, 32, 64, 128

As the purpose of your function is printing the powers of 2, you do not need to return the value. Hence, you can rewrite your function as the following:
int powers(int N) //here N=128
{
if(N==2){
System.out.print(N + ", ");
}
else if (N >2)
{
powers(N/2);
System.out.print(N + ", ");
}
System.out.println("");
return 0;
}
Also to handle the last extra comma you can return the previous step string and print outside the function.
String powers(int N) //here N=128
{
if(N==2){
return (N + "");
}
String prev = powers(N/2);
return (prev + ", " + N);
}

I think this would be a more elegant way to achieve this. Improvements are supposed to be:
Use bit shifting when possible to gain some
performance.
Fix comma placement for all cases of input N
More elegant looking code
int powers(int N) //here N=128
{
if (N < 2) return 0;
powers(N >> 1); // Right shifting achieves division by 2 but a lot faster.
if (N > 3) System.out.print(", "); // Fixing comma placement for all cases of N.
System.out.print(N);
return 0;
}

Why are we making the assumption that the input N is already a power of 2? Besides, 2 ^ 0 = 1, should that be in the result as well?
public int power(int num) {
if (num <= 0)
return -1;
else if (num <= 1) {
System.out.print(1);
return 1;
} else if (num <= 2) {
System.out.print(1 + ", " + 2);
return 2;
} else {
int result = 2 * power(num / 2);
System.out.print(", " + result);
return result;
}
}
This works even if you give 131 as the input.

Related

I need a little help debugging a small recursive function

int n is the number it will start from, int m is the number of multiples it will display.
its printing out the correct number of multiples but the multiples are not in the correct
order. For multiples(2, 5) it would print out 2, 4, 8, 16, 32. I understand why it is doing
that because it gets called with n+n. But I can't figure out how to add n correctly so it
displays 2, 4, 6, 8, 10, 12. I've tried with setting variable to n but it doesn't add right.
any help appreciated thNks! code below
public static void multiples(int n, int m)
{
if(m == 0){return;}
else{
System.out.print(n + ", ");
multiples(n + n, m - 1);}
}
}
You can print things in the correct order without adding any additional arguments by multiplying by m and doing the printing after the recursive call:
public static void multiples(int n, int m) {
if(m > 0) {
multiples(n, m - 1);
System.out.print((n * m) + ", ");
}
}
If you also want to lose the spurious trailing comma:
public static void multiples(int n, int m) {
if(m > 0) {
multiples(n, m - 1);
if(m > 1) {
System.out.print(", " + (n * m));
} else {
System.out.print(n);
}
}
}
Yet another option would be to return the values generated. That gives you more flexibility — you can then print them or use them in any subsequent operations as you see fit.
public static ArrayList<Integer> multiples(int n, int m) {
if(m > 0) {
ArrayList<Integer> result = multiples(n, m - 1);
result.add(n * m);
return result;
} else {
return new ArrayList<Integer>();
}
}
You can also send an initial value of 'n' as a parameter.
public static void multiples(int n, int m, int increment) {
if(m == 0) {
return;
} else {
System.out.print(n + ", ");
multiples(n + increment, m - 1, increment);
}
}
Actually, the method exactly does what it should do: print out the multiples. In your example the multiples are 2, 2 times 2 = 4, 2 times 2 times 2 = 8, 2 times 2 times 2 times 2 = 16, 2 times 2 times 2 times 2 times 2 = 32.
If you want to print out additions, it might be something like:
public static void multiplesHelper(int n, int m, int increment) {
if(m == 0) {
return;
} else {
System.out.print(n + ", ");
multiples(n + increment, m - 1, increment);
}
}
public static void multiples(int n, int m) {
multiplesHelper(n, m, n);
}
Example call would be then multiples(2, 6);

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);

Hailstone recursion not working in Java

I am trying to write a simple Java program to compute a hailstone sequence using recursion. A hailstone sequence is basically: take a given integer n - if even, the next integer in the sequence is n/2, if odd, the next integer in sequence is n * 3 + 1. I'm trying to return a string with each number separated by a comma, but my algorithm isn't working. Can someone explain why? Thanks!
public static String recursion (int n) {
String s = "";
if (n != 1) {
if (n % 2 == 0) return s + String.valueOf(recursion(n / 2)) + ", ";
else return s + String.valueOf(recursion((3 * n) + 1)) + ", ";
}
else return s + String.valueOf(1);
}
public static void main(String[] args) {
System.out.println(recursion(435));
}
the problem is, you don't print the actual number n. Change your code to:
public static String recursion (int n) {
//set s to the number n
String s = "" + n;
if (n != 1) {
//change position of the separator
if (n % 2 == 0) return s + ", " + recursion(n / 2);
//change position of the separator
else return s + ", " + recursion((3 * n) + 1);
}
else return s;
}
EDIT:
btw. you don't need String.valueOf(), since the result is already a String

write an algorithm to find the maximum value

Example:
numbers are [1, 2, 3] and u have +, *
max value is 1+2*3
example [1, 1, 1] , ans is 1+1+1
I can think of a simple recursive algorithm:
private static double helper(double[] arr, int s, int e) {
System.out.println("s= " + s + " e= " + e);
//base case: if single elem, return that eleme
if (e==s) {
return arr[s];
} if (s+1==e) {
return Math.max(arr[s]+arr[e], arr[s]*arr[e]);
} else if (s>e) {
//this should never happen
throw new UnsupportedOperationException("invalid operation");
}
//int mid = s+ ((e-s)/2);
int mid=s;
double fMax = Double.MIN_VALUE;
for (mid=s;mid<e;mid++) {
//divide and conqr route
double lres = helperDQ(arr,s, mid);
double rres = helperDQ(arr,mid+1, e );
System.out.println("s= " + s + " e = " + e + " m = " + mid + " lres= " + lres + " rres= " + rres);
fMax = Math.max(fMax, Math.max(lres*rres, lres+rres));
}
return fMax;
}
private static double findMax(double[] arr) {
return helper(arr, 0, arr.length-1);
}
Is there a better way to do instead of this recursive way? We can prune the recursion by checking for s, e so we dont end up recursing same thing multiple times.
Can't think of an easy dynamic programming approach way.
Any suggestions?
This can actually be solved a lot easier, using some simple math. For any two numbers a and b, the following applies: unless either a = 1 or b = 1 is given, a * b >= a + b is given (assuming a >= 1 and b >= 1). This applies recursively to any set of numbers. Thus the maximum will always be achieved by
int maxNum(int[] nums){
int x = 0;
for(int n : nums)
if(n == 1)
x += n;
else
if(x == 0)
x = n;
else
x *= n;
return x;
}
If the set of numbers is order.

Listing the total sum of all possible sums in a set with constraints

I am keen to find out the following:
Given a set with N elements, my friend and I are playing a game.I always make the first move.
We can only remove either the first or the last element with 50% chance each.We take alternate turns in the game.If only one element remains,we can remove it for sure.What is the expected sum that I can collect?
For example:N=2 {10,20} Possible sets that I can collect are {10},{20}.
So expected sum is 0.5*10+0.5*20=15.
My approach:
Since probability of getting a possible sum is equal in all cases,we only need to compute the sum of all possible sums and then multiply it by (0.5)^N/2.
I tried to use recursion to compute the required sum:
f(i,j)-computes the sum between i and j recursively
f(i,j)=2*a[i]+func(i,j-2)+func(i+1,j-1)+func(i+1,j-1)+func(i+2,j)+2*a[j]);
Initial call f(1,N)
But the approach doesn't seem to work. What should I do?
Complete function is below:
class CandidateCode {
static long v[][] = new long[1003][1003];
public static long func(int a[], int i, int j) {
if (i == j)
return v[i][j] = a[i];
if (v[i][j] != 0)
return v[i][j];
else {
if (i > j - 2 && i + 1 > j - 1 && i + 2 > j)
return (v[i][j] += 2 * a[i] + 2 * a[j]);
else
return (v[i][j] += 2 * a[i] + func(a, i, j - 2) + func(a, i + 1, j - 1) + func(a, i + 1, j - 1)
+ func(a, i + 2, j) + 2 * a[j]);
}
}
public static void main(String args[]) {
int n;
int a[] = { 0, 6, 4, 2, 8 };
n = a.length - 1;
System.out.println(func(a, 1, 4) / Math.pow(2, n / 2));
}
}
This problem can be solved by applying dynamic programming.
First, we have the state of the game is (player ,start, end) ,which indicates the current player, and the range of values that's available in the original set. At the beginning, we start at player 0 and start is 0, end is N - 1.
Denote that the first player is 0 and the second player is 1, we have the expected value of player 0:
if(player == 0){
double result = 0.5*( set[start] + f(1, start + 1,end) ) + 0.5*(set[end] + f(1,start, end - 1));
}else{
double result = 0.5*( f(0, start + 1,end) ) + 0.5*(f(0,start, end - 1));
}
So for each state, we can store all calculated state in a dp[player][start][end] table, which reduce the time complexity to O(2*N*N) with N is number of value in set.
Pseudo code:
double expectedValue(int player, int start, int end, int[]set){
if(start == end)
if(player == 0)
return set[start];
return 0;
if(already calculated this state)
return dp[player][start][end];
double result= 0;
if(player == 0){
result = 0.5*( set[start] + f(1, start + 1,end) ) + 0.5*(set[end] + f(1,start, end - 1));
}else{
result = 0.5*( f(0, start + 1,end) ) + 0.5*(f(0,start, end - 1));
}
return dp[player][start][end] = result;
}

Categories