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;
}
Related
I am working on a function, countH(), that is supposed to count the amount of times a given number appears in a linked list. For some reason, I cannot get this to work recursively. I have tried a number of different solutions but I guess I can't get something in the correct place. Sorry if I am asking the question poorly, I struggle to understand recursion formatting sometimes.
Here is the function:
public int count(int i) {
return countH(first, i);
}
private int countH(Node front, int i) { // TODO
int cter = 0;
if (front.next==null) {
return 0;
}
if(front.item == i)
cter++;
return countH(front, cter);
}
This is a late version of my code, I'm sure it was a bit better before I messed with it a bunch to try to get it to work
Thanks!
Every recursive implementation consists of two parts:
base case - that represents a simple edge-case for which the outcome is known in advance. For this task, the base case is a situation the given Node is null. Think about it this way: if a head-node is not initialed it will be null and that is the simplest edge-case that your method must be able to handle. And return value for the base case is 0.
recursive case - a part of a solution where recursive calls a made and where the main logic resides. In the recursive case, you need to check the value of a current node. If it matches the target value, then the result returned by the method will be 1 + countH(cur.next, i), otherwise it will be a result of the subsequent recursive call countH(cur.next, i).
Base case is always placed at the beginning of the method, followed by a recursive case.
And when you are writing a recursive part, one of the most important things that you have to keep in mind is which parameters change from one recursive call to another, and which remains the same. In this case, changes only a Node, the target value i remains the same.
public int count(int i) {
return countH(first, i);
}
private int countH(Node cur, int i) { // `front` replaced by `cur`
if (cur == null) { // not cur.next == null (it'll fail with exception if the head-node is null)
return 0;
}
// int cter = 0; // this intermediate variable isn't needed, it could be incremted by 1 at most during the method execution
// if(cur.item == i)
// cter++;
// return countH(cur, cter); // this line contains a mistake - variable `i` has to be passed as a parameter and `cter` must be added to the result returned by a recursive call
return cur.item == i ? 1 + countH(cur.next, i) : countH(cur.next, i);
}
Suggestion
Follow the comments in the code. I've left your original lines in place so that will be easier to compare solutions. Also, always try to come up will reasonable self-explanatory names for variables (as well as methods, classes, etc). For that reason, I renamed the parameter front to cur (short for current), because it's meant to represent any node, not first or any other particular node.
Side note
This statement is called a ternary operator or inline if statement
cur.item == i ? 1 + countH(cur.next, i) : countH(cur.next, i);
And it's just a shorter syntax for the code below:
if (cur.item == i) {
return 1 + countH(cur.next, i);
} else {
return countH(cur.next, i);
}
You could use either of these constructs in your code. The difference is only in syntax, both will get executed in precisely the same way.
In a linked list, you should have one element and from that you get the value and the next element. So your item could look like (I am omitting getters, setters and exception handling):
class Item {
Object value;
Item next;
}
Then your counter for a specific value could look like
int count(Object valueToCount, Item list) {
int result = 0;
if (valueToCount.equals(list.value)) {
result++; // count this value
}
if (value.next != null) {
result += count(valueToCount, value.next) // add the count from remainder of the list
}
return result;
}
public int count(int i) {
return countH(first, i);
}
private int countH(Node front, int i) { // TODO
if(front==null) {
return 0;
}
if (front.item == i) {
return 1 + countH(front.next, i);
} else {
return countH(front.next, i);
}
}
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;
}
}
}
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.
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.
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.