Recursion Driver Methods - java

public class FindSum
{
private static int sum(int n)
{
if (n==1)
return 1;
else
return n + sum (n-1);
}
public static int getSum(int n)
{
if (n>0)
return sum(n);
else
{
throw new IllegalArgumentException
("Error: n must be positive");
}
}
}
According to my book, this tests that n>0 before execution. I don't understand why that would be the case if the test "if (n>0)" comes after the algorithm. Shouldn't the two methods be flipped in order to accomplish this test?

The order they're written in doesn't matter, but rather the order of execution is critical.
Since getSum explicitly calls sum if the check is successful, then there's no worry about that check getting missed, so long as you call getSum.

In Java, the order the methods are in the class does not matter. notice that getSum() is calling sum().
So consider what would happen if we called getSum(0)?
The if condition would fail and nothing would happen, we would go straight to the error.
What if we called getSum(5)?
Then we would return sum(5).
But what is sum(5)? Now we find ourselves in the sum() method where we do our recursion stuff until we reach the base case, where we will finally return 1 + 14.

Related

what is wrapper function and how to use it?

For my homework, I am required to use a function called wrapper function to validate the parameter for a recursive function, which I don't understand what it means. All i understand from wrapper function is it does nothing but just wraps around a function eg:
private static int recursive(int n){
//do something
.
.
.
}
public static int recursiveWrap(int n){
return recursive(n);
}
I dont even know if the code above is the correct implementation for wrapper, but I know that it does nothing for the recursive function but just redundancy.
How am I supposed to use the wrapper function to validate the parameter? my recursive function has a base case which it will reach without the help of wrapper.
Well, a wrapper function would serve a purpose (otherwise there would be no reason for it to exist).
One such purpose could be to first validate the input before calling the actual recursive function (as is the case in your example), e.g. like this:
public static int recursive(int n){
//do something
.
.
.
}
public static int recursiveWrap(int n){
if( n < 0 ) {
throw new IllegalArgumentException("only positive arguments are allowed");
}
return recursive(n);
}
Another purpose could be to provide a convenient entry point for recursion, e.g. for quicksort (I'll just use int[] for simplicity reasons, a real world example would more likely use generic arrays or lists):
private static void recursiveQS(int[] array, int left, int right) {
//actual implementation here
}
//that's what the user would call
public static void quickSort(int[] array) {
recursiveQS(array, 0, array.length);
}
Why would you want to use wrapper functions? There are multiple possible reasons:
Keep the recursive function as simple as possible.
Validation checks often need to be done once so doing it in the recursive function would execute unnecessary code (and thus result in lower performance).
Provide a simple entry point for callers and handle any parameter mapping, setup etc. in the wrapper.
For more general purpose recursive functions there might be special validation or setup that only applies to certain situations and types of parameters. In those cases you might want to provide special wrapper functions for the special cases, i.e. you again keep the recursive function as simple as possible.
You are in the right direction.
Before calling the existing recursive method, you need to validate the parameter and take some action if the parameter is invalid
You haven't given the details on what to validate.
Example: If the parameter n should be within 1 to 10, you can add an if check to do that validation
public static int recursiveWrap(int n) {
if (n < 0 || n > 10) {
//some action
}
return recursive(n);
}
some action - can be anything like throwing an exception or returning a default result (maybe after logging a warning message).
In Java, usually a IllegalArgumentException is thrown to denote the argument passed is invalid.
if (n < 0 || n > 10) {
throw new IllegalArgumentException("The parameter value must be between 1 and 10 (inclusive)");
}
From my quick research on the subject, it seems the goal is to have a function validate the integer before calling the recursive function to avoid errors. For example, if I was writing a recursive function for calculating the factorial of an integer, I would want to make sure the integer is positive or zero before calling my method.
public int factorial(int n)
{
if(n == 0)
{
return 1;
}
return n * factorial(n-1);
}
public int factorialWrapper(int n)
{
if(n < 0)
{
return 0;
}
return factorial(n);
}
A wrapper for a recursive function is nothing more than a function which has
the responsibility of calling a recursive function.
Why it is used:
1)For providing a user user-friendly way of using the recursive function (since the parameters of a recursive function can be sometimes cryptic for the user and they have default values which make the function work for the most time)
2)For validation.
The following example will display all possible combinations of {0, 1, 2, 3}
in a length of 4. The function backtracking() is a wrapper for back(int)
I have written the following code in C++, if you want to translate it into java just
replace the two functions with static functions in your Java main class, replace cout with System.out.println();, remove the #include directive and `using namespace std;
and it will work;
#include<iostream>
using namespace std;
int a[4];
void back(int i)
{
if(i == 4)
{
for(int j = 0;j < 4;j++)
cout << a[j] << ' ';
cout << endl;
}
for(int j = 0; j < 4; j++)
{
a[i] = j;
back(i+1);
}
}
void backtracking() {
back(0);
}
int main() {
backtracking();
return 0;
}

static and non-static difference in Kth Smallest Element in a BST

In this problem, if I make the count variable in the second line static, as shown, the kthSmallest() method computes the wrong answer. If the variable is instead made non-static then the correct answer is computed. Non-static methods can use static variables, so why is there a difference?
class Solution {
public static int count = 0;
public int res = 0;
public int kthSmallest(TreeNode root, int k) {
inorder(root,k);
return res;
}
public void inorder(TreeNode root, int k) {
if (root == null) return;
inorder(root.left,k);
count++;
if (count == k) {
res = root.val;
return;
}
inorder(root.right,k);
}
}
I see no reason why the result of a single run of your kthSmallest() method would be affected by whether count is static, but if you perform multiple runs, whether sequentially or in parallel, you will certainly have a problem. count being static means every instance of class Solution shares that variable, which you initialize once to zero, and then only increment. A second run of the method, whether on the same or a different instance of Solution, will continue with the value of count left by the previous run.
Making count non-static partially addresses that issue, by ensuring that every instance of Solution has its own count variable. You still have a problem with performing multiple kthSmallest() computations using the same instance, but you can perform one correct run per instance. If you're testing this via some automated judge then it's plausible that it indeed does create a separate instance for each test case.
But even that is not a complete solution. You still get at most one run per instance, and you're not even sure to get that if an attempt is made to perform two concurrent runs using the same instance. The fundamental problem here is that you are using instance (or class) variables to hold state specific to a single run of the kthSmallest() method.
You ought instead to use local variables of that method, communicated to other methods, if needed, via method arguments and / or return values. For example:
class Solution {
// no class or instance variables at all
public int kthSmallest(TreeNode root, int k) {
// int[1] is the simplest mutable container for an int
int[] result = new int[1];
inorder(root, k, result);
return result[0];
}
// does not need to be public:
// returns the number of nodes traversed (not necessarily the whole subtree)
int inorder(TreeNode root, int k, int[] result) {
if (root == null) {
return 0;
} else {
// nodes traversed in the subtree, plus one for the present node
int count = inorder(root.left, k, result) + 1;
if (count == k) {
result[0] = root.val;
} else {
count += inorder(root.right, k, result);
}
return count;
}
}
}

Having trouble understanding return type placement( Big Java Ex 6.8)

Currently on the chapter in my book where we talk about for loops and loops. I have sometimes come across an issue where the method needs me to return something. For example consider my code
below. Basically the exercise is to get all the factors in ascending order. Now heres the issue
As you can see I need a return statement outside of the for loop. Now I guess my book didn't exactly explain this properly, or I didn't understand the concept
of return properly in java, but does our return statement always have to be in the most outer indentation if you will?
The thing is, I don't really want to return anything outside of the for loop. I just want to return i upon that condition. Why doesn't java let me do this?
Whats a good counter-action?
Ever since I started learning loops and for loops, I have been having trouble understanding this. I guess I could just system.out.println(i) instead of returning it? But then what should I return? I could also make it a void type, and then make another method to print it, I guess?
class factors{
private int num;
public factors(int num)
{
this.num = num;
}
public int getFactors()
{
for(int i = 1 ; i<num ; i++)
{
if (num % i == 0)
{
return i;
}
}
// I NEED TO PUT A RETURN STATEMENT HERE
}
}
public class test{
public static void main(String [] args)
{
factors fact = new factors(20);
System.out.println(fact.getFactors());
}
}
IT WORKS NOW ( I dont particularly like my solution)
class factors{
private int num;
public factors(int num)
{
this.num = num;
}
public void getFactors()
{
for(int i = 1 ; i<num ; i++)
{
if (num % i == 0)
{
System.out.println(i);
}
}
}
}
public class test{
public static void main(String [] args)
{
factors fact = new factors(20);
fact.getFactors();
}
}
The thing is, I don't really want to return anything outside of the for loop. I just want to return i upon that condition. Why doesn't java let me do this?
Java lets you do that. There is nothing wrong with returning inside the loop upon reaching the condition.
Java allows you to have multiple return statements, so adding another return 0; after the loop is allowed.
Java returns once it hits the first return statement, and other return statements are not executed (the method isn't executed anymore) (except for some rare edge cases with try-catch and return, but thats another story entirely).
But why is it required?
Java requires that for all possible paths there exists a return with the proper type. Even if you yourself can proof mathematically that the path Java complains about is never taken, the compiler might not be able to prove that the path is not possible at runtime. So you simply need to add an return there with a dummy value.
In your concrete example, there is a condition in which the loop gets never executed. If num <= 0, then the loop condition is never satified and the entire loop body is skipped. Without the return,the method is invalid, because you can't return nothing from an method with return type int.
So, in your example, the compiler is actually smarter then you, and prevents you from making a mistake - because it found the path you thought wouldn't occur.
new factors(-1).getFactors(); // you don't check the passed value at all ;)
From your comments, it seems that you want to return all factors. In java, you return once, and only once, from a function. This means you have to aggregate the results and return a List or array of values:
public List<Integer> getFactors(int num) {
List<Integer> factors = new ArrayList<>();
for (int i = 1 ; i<num ; i++)
{
if (num % i == 0)
{
factors.add(i);
}
}
return factors;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new factors(20).getFactors());
// prints a comma-separated list of all factors
}
does our return statement always have to be in the most outer indentation if you will?
No.
However, all potential code paths must return something. Consider this structure:
for(int i = 1 ; i<num ; i++)
{
if (num % i == 0)
{
return i;
}
}
What happens if num is a value where the loop itself is never entered? Or what happens if the if condition is never satisfied? No return statement would ever be encountered, which is invalid.
The compiler has to guarantee that the method will return something, under any and all potential runtime conditions. So while it's perfectly valid to return from within the loop, you also must provide logic for what to return if that return statement is never reached.
Java doesn't let you do that because what happens if the if (num % i == 0) is never true?
The methods return type is int, so it has to return an int. And it's possible that the if statement could be false, not every condition is covered with a return statement.
So if you wanted to you could return something like -1, or another invalid value. Then you know that the function didn't find what it was looking for.

Return statment not working in Java

I have been trying a small code to learn about recursion in java. Wrote the below method to implement linear search using recursion. But when I call this method with an array and the variable to search as input and when the method reaches the return statement, it is not exiting the method. Instead, after executing the statements in the if loop, it's once again entering the else loop.
I have 2 questions.
1) Why is it not exiting the method on reaching 'return' ?
2) Why is it entering the else loop after executing the if loop ?
What am I doing wrong here ? Can someone please take a look and help me.
linearRecursiveSearch(Constants.INPUT_INT_ARRAY, Constants.INPUT_INT_ARRAY[0], Constants.NUMBER_TO_SEARCH);
int count = 0;
public <T> void linearRecursiveSearch(T[] array,T tmp, T value) {
count++;
if (tmp == value) {
System.out.println("The value has been found");
return;
} else {
for (int i = count; i < array.length; i++) {
T tmp1 = array[i];
linearRecursiveSearch(array,tmp1, value);
}
}
}
1) Why is it not exiting the method on reaching 'return' ?
It is exiting the method that invoked return.
2) Why is it entering the else loop after executing the if loop ?
The method that invoked return is not invoking the else loop. However there are other invocations of the method that are, and they are queued up to resume after the method that does invoke return completes.
The point of confusion is that there is more than one invocation of the method and they are not all calling return.
Perhaps it will help to recall what happens when a method invocation occurs, that is the state of the current method is pushed onto a stack. Space is then reserved on the stack for the new invocation and then that method is invoked. Once that method completes, its state is popped from the stack. Its return value is made available and the previous method that is now at the top of the stack is resumed.
During recursion, the same method may be pushed on to the stack hundreds of times. That means the method could be called hundreds of times, and then each method will be resumed hundreds of times as the stack unwinds. Thus just because the method that is currently being invoked calls return (and exits) it does not mean that all of the other queued up instances will too. In fact it actually means that the previous method (the one that called this method) will resume.
Consider the following version, notice that it does not contain a for loop or any global state:
public <T> int linearRecursiveSearch(T[] array, T targetValue) {
return linearRecursiveSearch( array, targetValue, 0 );
}
private <T> int linearRecursiveSearch(T[] array, T targetValue, int i) {
if ( i >= array.length ) {
return -1;
} else if (array[i] == targetValue) {
// == or .equals, or Comparator? task for the reader
return i;
} else {
return linearRecursiveSearch(array, targetValue,i+1);
}
}
If I understand your problem this may be the solution
import groovy.util.logging.Slf4j
import org.junit.Test
#Slf4j
class MyTest {
#Test
public void myTest(){
int count = 0;
Integer[] input= [1,2,3,4,5,6,7]
linearRecursiveSearch(input,5,0)
}
public <T> void linearRecursiveSearch(T[] array, T value,int count) {
count++;
if (array[count] == value) {
System.out.println("The value has been found");
return;
} else {
linearRecursiveSearch(array, value,count);
}
}
}

I am trying to create a circular LinkedList Please tell me if its a correct way to do it

i have implemented logic like if i am giving a index that is not yet there then it will change the index to the reminder (Same like rotated i guess ).
import java.util.LinkedList;
public class MycircularlinkedList extends LinkedList {
private static int count = 0;
public Object get(int i) {
System.out.println("count==" + count);
if (i > count) {
i = i % count;
return super.get(i);
} else {
return super.get(i);
}
}
public boolean add(Object o) {
super.add(o);
count++;
return true;
}
public void add(int i, Object o) {
if (i > count)
i = i % count;
super.add(i, o);
count++;
}
}
A couple of points I can see:
count is static, this means you're only ever going to have one number here. Probably not what you want
count is redundant, use Collection#size()
The great thing about mod (%) is that it works for all numbers, you don't need to have the conditional. 2 % 12 == 14 % 12 == -10 % 12
If you're getting rid of the count property, you can get rid of your overridden #add(Object o) logic and just do return super.add(o);
I find some problem with your code: if count ==0 and if I use the method add(7,obj) ,then 7%0 will throw ArithmeticException.count should be declared to private since you may have two instances of your class.Also,you need to check
whether poll\offerLast method satisfies your needs,since you cant restrict
any client code to avoid using them.Finally,clone\readObject\writeObject
need to be overrried to include the count variable.
You're close.
(1) The term "circular linked list" is well-known to mean a list where the tail links back to the head (and vice versa if it's a doubly-linked list). Yours is more like a "circular buffer" stored in a linked list. We could call it LinkedListCircularBuffer or something.
(2) The class should be parameterized by the element type, thus
public class LinkedListCircularBuffer<E> extends LinkedList<E> {
#Override
public E get(int i) {
return super.get(i % size()); // simpler and faster without an "if"
}
}
(3) You can call size() instead of all the code to maintain another count.
(4) Your add(int i, Object o) method doesn't support the case where i == size(), but you can fix that by not overriding add() at all.
(5) Overridden methods need the #Override annotation.
(6) It's good style to always put braces around each "then" and "else" clause. Code like
if (i > count)
i = i % count;
is fragile, e.g. adding a println() statement into that "then" clause will break it.

Categories