I need to convert the code below to a recursive method without using global variables and using only one parameter.I Searched the topics already there is no code with one parameter and doesnt use the global variables.
public boolean isPrime(int x){
for(int i=2;i<x;i++)
if(x%i==0) return false ;
return true;
}
Ok, as for your requirements:
Without using global variables.
Using only one parameter.
And, based on:
it come up in one of my university exams
There a couple of aspects to take into account:
If you pass an instance of a Class you are passing only one variable, and as Classes can have multiple variables inside...
They do not state if you can call multiple functions inside, so, again, this is a hint or clue, of what can you do. So, two solutions for you:
Solution 1 (Using Classes)
class RecursVar {
int x;
int i = 2;
RecursVar(int x) {
this.x = x;
}
}
public boolean isPrimeRecurs(int x){
return isPrime(new RecursVar(x));
}
boolean isPrime(RecursVar recursVar) {
if(recursVar.x % recursVar.i == 0)
return false;
if (++recursVar.i >= recursVar.x)
return true;
return isPrime(recursVar);
}
Solution 2 (Cleaner approach without using Classes but based in that the function that can have only one parameter is isPrime )
boolean isPrime(int x) {
return checkForPrime(x, 2);
}
boolean checkForPrime(int x, int i) {
if (i >= x) return true;
if (x % i == 0) return false;
return checkForPrime(x, ++i);
}
Again, this solutions are based on that many exams require a little creativity and maybe that was the aim of this case.
This cases should not be used in production, they are slow and
prune to make honor to this site (StackOverFlow) with a sweet
java.lang.StackOverflowError
It's an interesting problem.
If you can use java 8, you can solve the problem as followed (note that the case isPrime(2) needs to be checked with an additional if condition):
package test;
import java.util.function.Function;
public class Test {
public static void main(String[] args) {
System.out.println(isPrime(13));
}
private static Function<Integer, Boolean> fun;
public static boolean isPrime(int x) {
fun = i -> {
if (i > 2) return (x%i != 0) && fun.apply(i-1);
else return (x%i != 0);
};
return fun.apply(x-1);
}
}
One of my schoolmates' topic accually recieve a solution here it is if you interested its quite brilliant
https://stackoverflow.com/questions/35660562/finding-prime-numbers-recursively-with-using-only-one-parameter?noredirect=1#comment59001671_35660562
Related
I'm a 2nd Year Student and we're currently studying Java. I'm quite confused on how to do the two on the title especially here in the exercise that was provided for us. Hoping to get inputs and help. Thank you!
Question: Create an interface named Comparison whose method can be used to compare two
Time objects. The methods will include isGreater, isLess, and isEqual. Create another class that will implement these methods.
My code so far:
import java.util.*;
interface Comparison {
boolean isGreater(Time x, Time y);
boolean isLess(Time x,Time y);
boolean isEqual(Time x, Time y);
}
public class Time implements Comparison {
int am, pm;
public boolean isGreater(Time x, Time y) {
if (am > pm) {
System.out.print("True");
}
else
System.out.print("False");
}
public boolean isLess(Time x,Time y) {
if (am < pm) {
System.out.print("True");
}
else
System.out.print("False");
}
public boolean isEqual(Time x, Time y) {
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Enter your first number: ");
int x = new Time();
System.out.println("Enter your second number: ");
int y = new Time();
}
}
thank you for your help!
if I correctly understand your query that you are trying to compare 2 different values of time if it is the only case then please refer the below code else please explain bit more about your requirement so i could correct the source code to help you.
as per your source code AM and PM are unrelated with time. we can pass time in 2 ways.
create own time class and used it.
use dateTime/Date/calendar classes which provide time values.
Step : 1 => create Main class.
Step : 2 => create an interface outside the class. make time data type to long.
interface Comparison {
boolean isGreater(long xTime, long yTime);
boolean isLess(long xTime, long yTime);
boolean isEqual(long xTime, long yTime);
}
Step :3 => create a TimeManager[anyname] class to implement comparison interface. implement the interface methods.
class TimeManager implements Comparison {
#Override
public boolean isGreater(long xTime, long yTime) {
return xTime > yTime ? true : false;
}
#Override
public boolean isLess(long xTime, long yTime) {
return xTime < yTime ? true : false;
}
#Override
public boolean isEqual(long xTime, long yTime) {
return xTime == yTime ? true : false;
}
}
Step :4 => write calling statement into main method and pass time using date object from java.utils
public static void main(String[] args) {
System.out.println("Enter your first number: ");
long x = new Date().getTime();
System.out.println("Enter your second number: ");
long y = new Date().getTime();
}
i hope this would help you.
Java compiler does not allow 2 public outer(top level) classes in the same java file
If a java file has a top level public class, then the file name should match the top level public class name
the comparison of am and pm seems unrelated to Time as per the sample code
in real code, Time references need to be checked for null values
A method with return type boolean should return a boolean value
Sample code
public boolean isGreater(Time x, Time y) {
if (x == null && y == null) {
return true; // you need to decide whether this is true or false
} else if (x == null || y == null) {
return false;
}
return x.getTime() > y.getTime(); // assumes getTime() returns a number
}
I have read the similar question and learnt that it is not possible to use a ternary operation instead of if statement, which does not have else statement. Because, if-without else statements are binary not ternary. My question is more best-practice.
In my code, there are lots of code snippet like that
if( calculation < 1 ){
calculation= 0;
}
I would like to shorten these with tenary. Is it a good practice to change these statements with the following.
calculation = calculation < 1 ? 0 : calculation;
You could create a class (or classes) that would create a nice fluent API. Such that your line would be:
calculationTo = replace(calculationTo).with(0).when(calculationTo < 1)
In my opinion it doesn't read much better than a standard if statement, but it also depends on the conditions that you have.
Example implementation:
public class Replacer<T> {
private final T value;
private T replacementValue;
private Replacer(T value) {
this.value = value;
}
public static <V> Replacer<V> replace(V value) {
return new Replacer<V>(value);
}
public Replacer<T> with (T replacementValue) {
this.replacementValue = replacementValue;
return this;
}
public T when(boolean condition) {
if (condition) {
return replacementValue;
} else {
return value;
}
}
}
import static somepackage.Replacer.replace;
public class Main {
public static void main(String[] args) {
int calculationTo = 3;
calculationTo = replace(calculationTo).with(0).when(calculationTo < 1);
}
}
You might expand it or make condition a function so it can be used with lambda, etc. I would also make method with return object of different class (e.g. ReplacerWithValue) so that calling with twice in one chain would result in compilation error.
Since you're asking for a best practice, I'll point out something where you could do better and then I'll tell you why I like the ternary operator.
Let me rephrase you're code snippet:
if (calculatedValueAfterStep1 < 1) {
calculatedValueAfterStep2 = 0;
} else {
calculatedValueAfterStep2 = calculatedValueAfterStep1;
}
When you read your code and somebody asks you "what does 'calculation' represent?" then you cannot answer this question without asking for the line number. The meaning of "calculation" changes over the course of the program code. If you cannot explain what a variable means, you cannot give it a good name. This is why I like my Version better. There is a clear Definition of what meaning the variables "calculatedValueAfterStep1" and "calculatedValueAfterStep2" are. Yes, the names are bad. Change them to your domain accordingly.
Now when you look at the code, you'll notice that "calculatedValueAfterStep2" is not declared. So let's Change the code:
int calculatedValueAfterStep2 = -1;
if (calculatedValueAfterStep1 < 1) {
calculatedValueAfterStep2 = 0;
} else {
calculatedValueAfterStep2 = calculatedValueAfterStep1;
}
Now it gets ugly. The same person asking the earlier question will now ask "why is 'calculatedValueAfterStep2' initialized with '-1'?". So here comes the ternary operator:
int calculatedValueAfterStep2 = (calculatedValueAfterStep1 < 1) ? 0 : calculatedValueAfterStep2;
beautiful!
below the code is using a private method to add to the variable count. Below that variable are conditionals which by my understanding, will not run until the recursion stack traces upword. Am I correct? My test is failing, and I am trying to see if it is because my code is wrong or I'm using recursion wrong.
public boolean containsRightRedEdge() {
int count = 0;
count += containsRightRedEdge(root);
if(count > 0) return true;
return false;
}
private int containsRightRedEdge(Node n) {
if (n == null) return 0;
if (isRed(n.right)) {
return 1;
}
return containsRightRedEdge(n.left) + 0 + containsRightRedEdge(n.right);
}
I would say you are using recursion pretty much correctly, but your choice of method names could be less confusing, and your logic could be simplified.
I am not too familiar with the algorithm you're trying to implement, but you might try something like this:
public boolean containsRightRedEdge(Node root) {
return getNumRightRedEdges(root) > 0;
}
private int getNumRightRedEdges(Node n) {
if (n == null) return 0;
if (isRedEdge(n)) return 1;
return getNumRightRedEdges(n.left) + getNumRightRedEdges(n.right);
}
Generally a recursive method shouldn't have the same name as a non-recursive method. These method names communicate more clearly what each one does. Also your base cases might be wrong as you've got them written currently based on how I'm interpreting the algo should work. Of course, I don't know the code inside isRed() so I'm probably making wrong assumptions here.
The code above in my question, is the correct way to use recursion in this instance. I just had a typo which is now resolved. Leaving the question for other peoples reference.
This is my first question ever at StackOverFlow:
I am studying to interviews with the help of "Cracking the code interview" (5th Edition) book,
and I was solving the next problem:
Implement a function to check if a binary tree is a binary search tree (Q 4.5 pg 86).
Before we move on, I would like just to remind you the difference between a Binary search tree to a simple Binary tree:
A Binary search tree imposes the condition that for all nodes, the left children are less than or equal to the current node, which is less than all the right nodes.
So one of the solution the book offers is to scan the tree with In-Order traversal and on the fly to check if every node we visit is greater then the last one, and it assumes the tree can't have a duplicate values:
public static int last_printed = Integer.MIN_VALUE;
public static boolean checkBST(TreeNode n) {
if(n == null) return true;
// Check / recurse left
if (!checkBST(n.left)) return false;
// Check current
if (n.data <= last_printed) return false;
last_printed = n.data;
// Check / recurse right
if (!checkBST(n.right)) return false;
return true; // All good!
}
Now, up here everything is good, but then the book quotes :
If you don't like the use of static variables, then you can tweak this code to use a wrapper class for the integer, as shown below:
Class WrapInt {
public int value;
}
After reading on wrapper class all over here and in other websites I just couldn't come to the conclusion, why and how should I use the wrapper class here instead of the static variable?
This is a mechanism whereby you can create an instance of WrapInt, and pass it around. You then expose the value only to code that should know about it, instead of a public static non-final variable that can be accessed and changed from anywhere.
The reason you have the wrapper class is because Java primitives are pass-by-value; passing around an int and then updating it wouldn't propagate the change through the rest of your system.
This would look like this:
public static boolean checkBST(TreeNode n) {
WrapInt counter = new WrapInt();
return checkBST(n, counter);
}
public static boolean checkBST(TreeNode n, WrapInt counter) {
if(n == null) return true;
// Check / recurse left
if (!checkBST(n.left, counter)) return false;
// Check current
if (n.data <= counter.value) return false;
counter.value = n.data;
// Check / recurse right
if (!checkBST(n.right, counter)) return false;
return true; // All good!
}
Here you go:
public static boolean checkBST(TreeNode n) {
WrapInt i = new WrapInt();
i.value = INTEGER.MIN_VALUE;
doCheckBST(n, i);
}
private static boolean doCheckBST(TreeNode n, WrapInt last_printed) {
if(n == null) return true;
// Check / recurse left
if (!checkBST(n.left, last_printed)) return false;
// Check current
if (n.data <= last_printed.value) return false;
last_printed.value = n.data;
// Check / recurse right
if (!checkBST(n.right, last_printed)) return false;
return true; // All good!
}
If there is the possibility that there will run 2+ sorts at the same time. The static will be used for both sortings. Both sortings have access to the same static value.
//thread 1
Sorting A = new Sorting(5,9,8);
A.sort();
//thread 2
Sorting B = new Sorting(999,100,7);
B.sort();
We cant predict which/how the thread is processed.
So this could end up in
A.checkBST(5) // last_printed = 5
B.checkBST(999) // last_printed = ??
B.checkBST(100) // last_printed = ??
A.checkBST(9) // last_printed = ??
...
...
If every sort instance has his own last_printed, you won't have synchronisation issues.
I think this is more formal way how to avoid of public static context property (e.g for thread safety), which is not optimal approach in object programming. But there are standard Primitive wrapper classes as: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
which can be used instead of new classes. Generally Wrapper pattern can be more general than your example: What is a wrapper class?
The problem with static variable is that another class/method or something can modify it and it will break your code.
Can you make it like that:
Class WrapInt {
public int value=Integer.MIN_VALUE;
}
public static boolean checkBST(TreeNode n,WrapInt lastPrinted) {
if(n == null) return true;
// Check / recurse left
if (!checkBST(n.left,lastPrinted)) return false;
// Check current
if (n.data <= lastPrinted.value) return false;
lastPrinted.value = n.data;
// Check / recurse right
if (!checkBST(n.right,lastPrinted)) return false;
return true; // All good!
}
I'm writing a recursive method that checks each letter of the string to compare them. I'm having trouble making the "*" character match with any, and act as as many letters as needed. (Making it a wildcard)
I was wondering if someone can give me a hint on the algorithm that would be used?
Here is what I have so far.
public static boolean match(String x, String y) {
return match_loop(x, y, 0, 1);
}
public static boolean match_loop(String a, String b, int i, int s) {
try {
if (a == b) {
return true;
}
if (i >= a.length() && i >= b.length()) {
return true;
}
if (a.charAt(i) == b.charAt(i)) {
return match_loop(a, b, i + 1, s);
}
//(((...A bunch of if statements for my other recursion requirements
return false;
} catch (java.lang.StringIndexOutOfBoundsException e) {
return false;
}
}
public static void main(String[] args) {
System.out.println(match("test", "t*t")); // should return true
}
What I was thinking of doing is adding another arguement to the method, an int that will act as a letter backcounter. Basically I'm thinking of this
if a or b at char(i-s) (s originally being 1.) is a *, recall the recursion with s+1.
and then a few more different ifs statements to fix the bugs. However this method seems really long and repetitive. Are there any other algorithms I can use?
Do not use == for String value comparison. Use the equals() method.
if (a == b) should be if a.equals(b)
If you are using only one character("*") as a wildcard, I recommend you to use regular expression. Such as;
public static boolean match(String x, String y) {
String regex= y.replace("*", "(.*)");
if(x.matches(regex)) {
return true;
}
}
public static void main(String[] args) {
System.out.println(match("test", "t*t")); // should return true
}
I think it is easier to read the code this way.
Have a look at this algorithm. It returns all substrings that match the pattern, so you'll have to check whether the entire string is matched in the end, but that should be easy.
It runs in O(km) time, where k is the number of wildcards and m is the length of your input string.
This book will tell you exactly how to do it:
http://www.amazon.com/Compilers-Principles-Techniques-Alfred-Aho/dp/0201100886
Here's a simple Java implementation that might get you on track: http://matt.might.net/articles/implementation-of-nfas-and-regular-expressions-in-java/
Basically the industrial-strength implementation is a state machine. You deconstruct the regular expression - the string with the '*' in it - and create a graph for it. Then you recursively search the graph, for example in a breadth-first tree search.
Here's some discussion of different ways to do it, that will help illustrate the approach: http://swtch.com/~rsc/regexp/regexp1.html