does this count as a recursive function...if no, then what is the reason. Which changes would classify it as such...thanks
public class Recursion {
public static void recursionFunc(int beginning_value){
if (beginning_value != 0){
System.out.println(beginning_value);
recursionFunc(beginning_value - 1);
}
}
public static void main(String[] args){
recursionFunc(10);
}
}
A function that calls itself, directly or indirectly, is called recursive. Your function calls itself, so it is definitely recursive.
Here is an example of recursive functions that calls themselves indirectly:
static void funcA(int x) {
if (x <= 0) return;
if (x % 2 == 0) {
funcB(x-1);
} else {
funcC(x-1);
}
}
static void funcB(int x) {
funcA(x-1);
}
static void funcC(int x) {
funcA(x-2);
}
Your method is a recursive method. A method is considered to be recursive when it calls itself again. All recursion methods should some sort of exit built into it, otherwise the method will yield an Stackoverflow error.
Here is a recursive method that does not have a exit built into it:
static void callAgain() {
callAgain();
}
Here's more details on recursive methods:
http://danzig.jct.ac.il/java_class/recursion.html
Related
What is the difference between the following two methods:
public boolean recursionMethodOne(Node n) {
System.out.println(n.getValue());
return recursionMethodOne(n.next());
}
public void recursionMethodTwo(Node n) {
System.out.println(n.getValue());
recursionMethodTwo(n.next());
}
Which one do you use for recursion and what is the difference?
Thanks
Both your codes doesn't exits. You need to add a return for a test condition. For example:
public void recursionMethodTwo(Node n) {
if (n == null) {
// Standard way to exit a void function without executing remaing code
// note that return null; doesn't compile
return;
}
System.out.println(n.getValue());
recursionMethodTwo(n.next());
}
Returning a value or not depends on the kind of function.
For example if you need to calculate a factorial you need a result, if you need to print a list you don't.
So for your example seems that the method two is most closer to your needs.
Otherwise you need to ask yourself what is the returning boolean value of the function? If you have a nice answer to this question you can implement the code returning a value.
I want to know if there are basic ways to call a method multiple times. I am not allowed to use for, if, or else statements. I am suppose to write a method called test 1 and test 2, which calls the increase speed and decrease speed by 3 times. If anyone can offer me suggestions, I would appreciate it.
Requirements
increaseSpeed. The increaseSpeed method should add 10 to the speed
field each time it is called.
reduceSpeed. The reduceSpeed method should subtract 10 from the speed
field each time it is called.
write a method called test1 that calls increaseSpeed three times.
write a method called test2 that calls reduceSpeed three times.
program:
public void increaseSpeed()
{
speed += 10;
}
public void reduceSpeed()
{
speed -= 5;
}
public void test1(){
}
public void test2(){
}
}
You could simulate a for loop with a while loop:
public void test1() {
int i = 0;
while (i < 3) {
increaseSpeed();
++i;
}
}
Or, if you aren't allowed to use loops at all, you could just call the increaseSpeed three times:
public void test1() {
increaseSpeed();
increaseSpeed();
increaseSpeed();
}
We can also get more creative (a.k.a. pointless):
This first example requires Java 8, but it's a glorified FOR loop. You can replace 'forEach' with a map() or filter() that has an ignored output or one of the other Java stream processing items if you have an aversion to the word 'for'.
private static void test1() {
IntStream.range(0, 3).forEach(
i -> increaseSpeed()
);
}
This second example uses a switch + recursion because you also didn't mention anything about the 'switch' statement.
private static final int INITIAL_COUNT = 2; // 3 - 1
private static int numTimes = INITIAL_COUNT;
private static void test2() {
switch(numTimes) {
case 0:
numTimes = INITIAL_COUNT;
break;
default:
numTimes--;
test2();
break;
}
reduceSpeed();
}
Note that if you tried to submit either of these to a code review, you'll be rejected unless the project is run by a joker that doesn't care about code quality :)
You didnt mention while loop is prohibited, i assume it is okay to use it:
int i = 0;
while(i<3){
increaseSpeed();
i++;
}
Alternatively, you can either use do-while loop to implement your requirement or invoke the method 3 times..
public void test1(){
increaseSpeed();
increaseSpeed();
increaseSpeed();
}
public void test2(){
decreaseSpeed();
decreaseSpeed();
decreaseSpeed();
}
For more general "solutions" and hacks have a look at these: C: Looping without using looping statements or recursion and
https://codegolf.stackexchange.com/questions/33196/loop-without-looping.
Using the given methods, the most effective and simple way would be to invoke it 3 times in a row:
public void test1() {
increaseSpeed();
increaseSpeed();
increaseSpeed();
}
public void test2() {
decreaseSpeed();
decreaseSpeed();
decreaseSpeed();
}
A more flexible approach is using a recursive invocation, as described below:
public void test1() {
increaseSpeed(3);
}
public void test2() {
decreaseSpeed(3);
}
private void increaseSpeed(int numTimes) {
if (numTimes == 0) {
return;
}
increaseSpeed();
increaseSpeed(numTimes-1);
}
private void decreaseSpeed(int numTimes) {
if (numTimes == 0) {
return;
}
decreaseSpeed();
decreaseSpeed(numTimes-1);
}
Going a little bit beyond the question, if these tests model a real use case it probably is a good idea to review methods increaseSpeed() and decreaseSpeed() to prevent these multiple invocations.
Your test1 method should be recursive and it should take an Integer as parameter which will be the number of calls you want to make
So basically you should have something like this:
public void test1(int nbcalls) {
if (nbcalls-- > 0) {
increaseSpeed();
test1(nbcalls);
}
}
and you call you method like this :
test1(3);
You should do the same with test2(...) method
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
I have some trouble understanding the following recursive code:
public class recursive {
public static void main(String[] args){
helper(0) ;
}
public static void helper(int i){
int a=3;
if(i==a){
System.out.println("yes:"+i);
return;
}else{
for(;i<a;i++){
System.out.println("no:"+i);
helper(i+1);
System.out.println("end:"+i);
}
}
}
}
The Output is as follows:
no:0
no:1
no:2
yes:3
end:2 //why this is 2?
end:1 //why this is 1?
no:2
yes:3
end:2
end:0
no:1
no:2
yes:3
end:2
end:1
no:2
yes:3
end:2
I do not understand why the first end is 2. Can anyone explain how does the recursion work in this simple program?
try
public static void helper(int i){
int a=3;
if(i==a){
System.out.println("yes:"+i);
return;
}else{
System.out.println("no:"+i);
helper(i+1);
}
}
one idea of recursion is to do away with loops
Each call to helper has its own local value of i.
So when i==2, and you call helper(i+1), the next call to helper has i==3, but when it returns, it goes back to the previous helper invocation, for which i==2.
Something is very wrong here...
public class evenness {
public static Boolean isEven (Integer i) {
return (i % 2) == 0;
}
public static void main(String[] args) {
if (isEven(Integer i)) { //something wrong on this line.
System.out.print("YAY!");
}
}
}
Please help me sort it out!
You are supposed to give an Integer argument to the function isEven, for example 3 or 125.
I'm pretty sure that your IDE is telling you that it can't find the variable Integer. So you need to give a variable. The argument type is only required in the method definition.
For example:
int number = 4;
if(isEven(number)){
...
}
or more directly
if(isEven(4)){
...
}
Change
if (isEven(Integer i)) {
to something like
int i = 5;
if (isEven(i)) {
or
if (isEven(5)) {
You need to pass an integer to the method.
Just provide an argument where you call your method in main();
public class evenness {
public static Boolean isEven (Integer i) {
return (i % 2) == 0;
}
public static void main(String[] args) {
if (isEven(36)) { //something wrong on this line.
System.out.print("YAY!");
}
}
}
Following Java coding convention by changing the class name to Evenness.
public class Evenness
The method isEven(...) should accept int and return boolean. Both are primitive data types. This will make the program runs faster than using their wrappers. A wrapper is a reference type (object) that wraps a primitive type. For example, Integer wraps int and Boolean wraps boolean.
public static boolean isEven (int i) {
Send an argument to isEven(...)
if (isEven(2)) { // this line is now OK.