Programming Assignments-Recursion - java

Still learning and I cant seem to wrap my head on what seemed like an easy task.
The computeMethods method's is where im totaly stumped, however the reverse method i just keep getting back the same integer without it being reversed.
/****************************
* For Method Computemethods1 i must compute series
* b(x)=1/3+2/5+3/7..... +x/2x+1
* For method ComputeMethod2
* 1/2+2/3+......... x/(x+1)
*******************************/
public static int computeMethod1(int x){
if (x==0)
return 0;
if (x==1)
return 1;
return computeMethod1(x-1/3/(x-1))+computeMethod1(x-2/3/(x-2));
}
public static int computeMethod2(int x){
if (x==0)
return 0;
return computeMethod2((x-1)/(x-1)+1)+computeMethod2((x-2)/(x-2)+1);
}
/********************
* For method reverseMethod i must reverse a user given int
**********************/
public static int reverseMethod(int x){
int reversedNum=0;
if (x!=0)
return x;
reversedNum=reversedNum *10 +x%10;
return reversedNum+reverseMethod(x/10);
}
/******************
* For method sumDigits i must use recursion
* to sum up each individual number within the int
********************/
public static long sumDigits(long n){
if( n==0)
return 0;
if (n==1)
return 1;
else
return n+sumDigits(n-1);
}
}

For reverse method, you are using: if (x!=0) return x;
May be you need to use: if (x==0) return x. So the logic is, if the given argument is 0, then return 0, else return reversed number.
P.S.: As somebody mentioned in comentaries, please take care of types, so for the division you are better using float or double, and take care of operations precedence for correct result, so (x+1)/2 will be different from x+1/2.

For each of your methods, follow through your code for small x.
For example, computeMethod1 should return:
1/3 for x == 1, whereas at the moment it simply returns 1 (Note, the return type will need to be something other than int.).
1/3 + 2/5 for x == 2.
1/3 + 2/5 + 3/7 for x == 3.
For each x, notice how we can use the previous result i.e. computeMethod1(x - 1).
When you come across code that doesn't seem to do what you expect, make your code simpler and simpler until you can narrow down where the problem is, then hopefully it will be obvious what the problem is, or online documentation can tell you.

Related

Recursive binary search and return index of object

I'm having difficulty figuring out how I can return the index of an item in an array via the recursive binarySearch function I have below:
public static <AnyType extends Comparable<AnyType>> int binarySearch
(AnyType[] a, AnyType x)
{
int nMin = 0;
int nMax = a.length - 1;
int nMid = (nMin + nMax) / 2;
int compare = a[nMid].compareTo(x);
if(compare == 0)
return 1;
else if(compare == 1)
return binarySearch(Arrays.copyOfRange(a, 0, a.length/2), x);
else
return binarySearch(Arrays.copyOfRange(a, a.length/2, nMax), x);
}
The requirement is to write a BS function with the function header and not to modify it. My function works fine, however, as I modify the array through each level of recursion, I lose the original index. We are also required to return the index of the item we're searching for. My implementation will always return 1.
Is it even possible to do this without creating another method and calling it from within the binarySearch function?
So after much confusion from pretty much the entire 300 student class, the teacher addressed this during lecture and explained that we could, in fact, create another function to handle anything we needed (position in this case).
So what I did was just write a normal recursive binary search implementation and call that from the function the professor required to have included.
public static <AnyType extends Comparable<AnyType>> int binarySearch
(AnyType[] a, AnyType x)
{
return binarySearch(a, x, 0, a.length);
}
public static <AnyType extends Comparable<AnyType>> int binarySearch
(AnyType[] a, AnyType x, int nMin, int nMax)
{
if(nMin < nMax)
{
int nMid = nMin + (nMax - nMin) / 2;
if(x.comapreTo(a[nMid]) == -1)
return binarySearch(a, x, nMin, nMid);
else if(x.compareTo(a[nMid]) == 1)
return binarySearch(a, x, nMid+1, nMin);
else
return nMid;
}
rteurn -(nMin + 1);
}
Also, as a side note, I think my original question was poorly worded. I wasn't looking for a solution to the problem, I was more or less looking for confirmation in my thinking that the problem was impossible.
Recursive search by copying the array on each recursion is bad for performance.
Pass the entire array on recursion, with additional range values, i.e. start/end indexes to process.
This is faster, and will also allow you to immediately know the actual index of the found element, since index values are unchanged.
Update
If the method signature cannot be changed, then a few changes are needed:
int compare = a[nMid].compareTo(x);
if(compare == 0)
return 1;
If the element at index nMid is equal, that is the index to return, not 1.
else if(compare == 1)
return binarySearch(Arrays.copyOfRange(a, 0, a.length/2), x);
compareTo() returns a "positive integer", not necessarily 1, so test should be compare > 0.
Also, there is no need for the else part, since the if has unconditional return.
else
return binarySearch(Arrays.copyOfRange(a, a.length/2, nMax), x);
First, the last argument of copyOfRange() is exclusive, so it needs to be a.length, not nMax.
Since the recursive call is passing in a range not starting at 0, any index value returned must be offset, i.e. return binarySearch(...) + a.length/2.
Again, no need for else.
In addition to all the above, if the value doesn't exist, the code will eventually fail because copyOfRange() will create an empty array, and code doesn't handle that, causing a[nMid] with a value of 0 to throw an IndexOutOfBoundsException. Need to add code to handle that.

Java Recursion Fibonacci Value

Question:
How many calls are needed to recursively calculate the 7th Fibonacci value?
So this was a problem given to me and the answer was given to me as 41. Then I went to a professor because I didn't understand it, but I was given another answer. I think it was 25? (don't quote me on that) Then I went to another professor... and he told me the person who gave you this problem should have given you the sample code because there can be multiple ways to write this recursive function which would result in different amounts of calls.
So if this is true can you guys find different recursive functions that would result in a different amount of calls needed to get the 7th value of the sequence?
One way:
static long fibonacciR(int i)
{
if (i <= 1)
return i;
return fibonacciR(i - 1) + fibonacciR(i - 2);
}
Another way:
static final int f[] = {0,1,1,2,3,5,8,13,21,34,55,89,144};
static long fibonacciR2(int i)
{
if (i < f.length)
return f[i];
return fibonacciR2(i-1)+fibonacciR2(i-2);
}
In fact 'another' way is any number of other ways, depending on how big you make the table. When the table has two elements both methods are equal. When it has three there are 25 calls. When 4, 15. And so on.
Yet another way, to get specifically 25 calls:
static long fibonacciR3(int i)
{
if (i == 0)
return 0;
if (i <= 2)
return 1;
return fibonacciR(i - 1) + fibonacciR(i - 2);
}

Find median of randomly generated numbers

Qn (from cracking coding interview page 91)
Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated.
My question is: Why is it that if maxHeap is empty, it's okay to return minHeap.peek() and vice versa in getMedian() method below?
Doesn't this violate the property of finding a median?
I am using the max heap/min heap method to solve the problem. The solution given is as below:
private static Comparator<Integer> maxHeapComparator, minHeapComparator;
private static PriorityQueue<Integer> maxHeap, minHeap;
public static void addNewNumber(int randomNumber) {
if (maxHeap.size() == minHeap.size()) {
if ((minHeap.peek() != null)
&& randomNumber > minHeap.peek()) {
maxHeap.offer(minHeap.poll());
minHeap.offer(randomNumber);
} else {
maxHeap.offer(randomNumber);
}
} else {
if (randomNumber < maxHeap.peek()) {
minHeap.offer(maxHeap.poll());
maxHeap.offer(randomNumber);
} else {
minHeap.offer(randomNumber);
}
}
}
public static double getMedian() {
if (maxHeap.isEmpty()) {
return minHeap.peek();
} else if (minHeap.isEmpty()) {
return maxHeap.peek();
}
if (maxHeap.size() == minHeap.size()) {
return (minHeap.peek() + maxHeap.peek()) / 2;
} else if (maxHeap.size() > minHeap.size()) {
return maxHeap.peek();
} else {
return minHeap.peek();
}
}
The method has a shortcoming that it does not work in situations when both heaps are empty.
To fix, the method signature needs to be changed to return a Double (with the uppercase 'D') Also a check needs to be added to return null when both heaps are empty. Currently, an exception on a failed attempt to convert null to double will be thrown.
Another shortcoming is integer division when the two heaps have identical sizes. You need a cast to make it double - afetr all, that was the whole point behind making a method that finds a median of integers return a double in the first place.
Another disadvantage with this approach is that it doesn't scale well, for example to heap sizes that don't fit in memory.
A very good approximation algorithm is simply storing an approximate median with a fixed increment (eg. 0.10), chosen appropriate to the scale of the problem. For each value, if the value is higher, add 0.10. If the value is lower, subtract 0.10. The result approximates the median, scales well, and can be stored in 4 or 8 bytes.
Just do this ... else everything is correct:
return new Double(minHeap.peek() + maxHeap.peek()) / 2.0;

Recursive Exponent Method stack overflow

I already searched everywhere for a solution for my problem, but didn't get one. So what I'm trying to do ist use recursion to find out whats a passed integer variable's base to the power of the passed exponent. So for example 3² is 9. My solution really looks like what I found in these forums, but it constantly gives me a stack overflow error. Here is what I have so far.(To make it easier, I tried it with the ints directly not using scanner to test my recursion) Any idea?
public class Power {
public static int exp(int x,int n) {
n = 3;
x = 2;
if (x == 0) {
return 1;
}
else {
return n * exp(n,x-1);
}
}
public static void main(String[] args) {
System.out.println(exp(2,3));
}
}
Well, you've got three problems.
First, inside of the method, you're reassigning x and n. So, regardless of what you pass in, x is always 2, and n is always 3. This is the main cause of your infinite recursion - as far as the method is concerned, those values never update. Remove those assignments from your code.
Next, your base case is incorrect - you want to stop when n == 0. Change your if statement to reflect that.
Third, your recursive step is wrong. You want to call your next method with a reduction to n, not to x. It should read return x * exp(x, n-1); instead.

Recursive method with wrong parameter

This was my answer to a question in which I was supposed to convert an iterative method to a recursive method. The teacher told me I cant use a-=1 as a parameter... So they gave me 0 points..
When I run this it works as it supposed to be..
Could someone tell me why its wrong?
public int do(int a){
if(a==0){
return 1 ;
}else{
return a * do(a-=1);
}
}
The problem with your code is that you're reading the value of a and reassigning it with a -= 1 in the same expression, but the order of these operations is not specified. The statement:
return a * do(a -= 1);
could be implemented as:
temp = a;
a -= 1;
return temp * do(a);
which will do what you were probably expecting, or:
a -= 1;
return a * do(a);
which will multiply by the decremented value of a rather than its original value.
The correct way to write your function is:
public int do(int a){
if(a==0){
return 1 ;
}else{
return a * do(a-1);
}
}
Just pass the result of the subtraction as an argument, don't reassign the variable at the same time.
I assume that this is in java?
I see two big problems with this snippet.
do is a reserved keyword. It may cause compilation errors, so you should name your method something else.
Executing -= in a parameter call seems quite ambiguous. Will the negation operator run before or after the multiplication by a? The more clear operator to use would be simply the - operator, and it would complete with the same result.
That said, something like this might have been what the teacher was looking for:
public int calculateSomething(int a) {
if (a == 0) {
return 1;
} else {
return a * calculateSomething(a - 1);
}
}

Categories