function findNum(a, b) {
if (!b) {
b = 0;
}
if (a < 2) {
throw new Error('wrong');
}
if (a === 2) {
return 1 / a + b;
}
return findNum(a - 1, b + 1 / (a * (a -1)));
}
Is there any way to write this func w/o recursion and without using while in it?
Related
Why do I need to use return statement before recursively calling BubbleSort function?
without return statement : no output
void BubbleSort(int arr[], int n, int j)
{
if(n == 1)
return;
if(j == n - 1)
{
BubbleSort(arr, n - 1, 0);
}
if(arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
BubbleSort(arr, n, j + 1);
return;
}
with return statement : gives the correct output
void BubbleSort(int arr[], int n, int j)
{
if(n == 1)
return;
if(j == n - 1)
{
return BubbleSort(arr, n - 1, 0);
}
if(arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
BubbleSort(arr, n, j + 1);
return;
}
By specifying return keyword we are assure that the control of program will move to its caller.
BubbleSort(arr, n - 1, 0);
when you're executing this, without return keyword, it's calling self and the control is not returning to it's caller therefore rest of the code also executing and it does change the business which was not intended and you might getting some messy things to your result.
the following snippet might help you to understand it better:
if(j == n - 1)
{
BubbleSort(arr, n - 1, 0);
return; // returns to it caller.
}
This is a recursive check if this is a prime number -- is it correct?
public static boolean isPrimeRecursive (int n,int i){//i eqoual to n
if (n <= 1) {
return false;
}if (i==1){
return false;
}if(n%i==0){
return false;
}
return isPrimeRecursive(n,i--);
}
I wouldn't burden your user with that mysterious second argument but rather present a different method of just one argument, that first deals with numbers less than 2 and even numbers, and then calls into your recursive method with the proper arguments:
private static boolean isPrimeRecursive(int n, int i) {
if (i * i > n) {
return true;
}
if (n % i == 0) {
return false;
}
return isPrimeRecursive(n, i + 2);
}
public static boolean isPrime(int n) {
if (n <= 2 || n % 2 == 0) {
return (n == 2);
}
return isPrimeRecursive(n, 3);
}
public static void main(String[] args) {
System.out.println(isPrime(Integer.parseInt(args[0])));
}
With your code, you should start of i with a value of n-1 since n % n is always true of prime numbers.
Then in your condition (if (i == 1) { ... }, should return true because if the method reaches to 1, then it fulfills all other conditions.
Finally in your return statement return isPrimeRecursive(n, i++);, it is better to use ++i since i++ will increment after the execution of the function with the value of i.
public static boolean isPrimeRecursive (int n,int i){
if (n <= 1) {
return false;
}
if (i == 1) {
return true;
}
if(n % i == 0){
return false;
}
return isPrimeRecursive(n, --i);
}
In your main function, you will then use:
int n = 17;
System.out.println(isPrimeRecursive(n, n-1);
Another way of doing it is to always start i with a value of 2 and increment it's value. From there.
public static boolean isPrimeRecursive (int n, int i) {
if (n <= 2) {
return (n == 2) ? true : false;
}
if (i >= n) {
return true;
}
if (n % i == 0) {
return false;
}
return isPrimeRecursive(n, ++i);
}
Then you simple do:
int n = 17;
System.out.println(isPrimeRecursive(n, 2);
I've several confusion about tail recursion as follows:
some of the recursion functions are void functions for example,
// Prints the given number of stars on the console.
// Assumes n >= 1.
void printStars(int n) {
if (n == 1) {
// n == 1, base case
cout << "*";
} else {
// n > 1, recursive case
cout << "*"; // print one star myself
printStars(n - 1); // recursion to do the rest
}
}
and another example:
// Prints the given integer's binary representation.
// Precondition: n >= 0
void printBinary(int n) {
if (n < 2) {
// base case; same as base 10
cout << n;
} else {
// recursive case; break number apart
printBinary(n / 2);
printBinary(n % 2);
}
}
As we know by definition tail recursion should return some value from tail call. But for void functions it does not return any value. By intinction I think they are tail recursion but I am not confident about it.
another question is that, if a recursion function has several logical end, should tail recursion come at all logical ends or just one of the logical ends? I saw someone argued that only one of the logical ends is OK, but I am not sure about that. Here's my example:
// Returns base ^ exp.
// Precondition: exp >= 0
int power(int base, int exp) {
if (exp < 0) {
throw "illegal negative exponent";
} else if (exp == 0) {
// base case; any number to 0th power is 1
return 1;
} else if (exp % 2 == 0) {
// recursive case 1: x^y = (x^2)^(y/2)
return power(base * base, exp / 2);
} else {
// recursive case 2: x^y = x * x^(y-1)
return base * power(base, exp - 1);
}
}
Here we have logical end as tail recursion and another one that is not tail recursion. Do you think this function is tail recursion or not? why?
I am stuck doing an assignment for university. The task is to find a recursive and then dynamic programming way to calculate the length of the longest,consequent,ascending subsequence of an array. If the array for example is: {4 , -5 , -3, -2, 5, -2, 0, 3 , 2} the maximal length would be 4 with the subsequence {-5, -3, -2, 5}. I have trouble finding a recursive way and without a recursive way it's impossible to find a dynamnic way for me.
I have tried programming something but I know it's wrong and I am not sure how to fix it:
public static int length(int[] arr,int j)
{
if(arr.length == 1)
{
return 1;
}
if(j == 1)
{
if(arr[j-1] < arr[j])
{
return 1;
}
else
{
return 0;
}
}
else
{
int c = length(arr,j-1);
if(arr[j-1] < arr[j])
{
return 1 + c;
}
else
{
return 0;
}
}
}
Try this :
int length(int index, int previous)
{
if(arr.length == (index+1))
return 0;
else
if(arr[index] > previous)
return 1+length(index+1,arr[index]);
else return length(index+1,previous)
}
Maybe you don't need to give the array as argument in each recursive call by making a static variable,
Previous is the latest element of the subsequence
So I was writing a rock paper scissors game when I came to writing this function:
a is player one's move, b is player two's move. All I need to figure out is if player one won, lost, or tied.
//rock=0, paper=1, scissors=2
processMove(a, b) {
if(a == b) ties++;
else {
if(a==0 && b==2) wins++;
else if(a==0 && b==1) losses++;
else if(a==1 && b==2) losses++;
else if(a==1 && b==0) wins++;
else if(a==2 && b==1) wins++;
else if(a==2 && b==0) losses++;
}
}
My question is: What's the most elegant way this function can be written?
Edit: I'm looking for a one-liner.
if (a == b) ties++;
else if ((a - b) % 3 == 1) wins++;
else losses++;
I need to know exactly which language you are using to turn it into a strictly one-liner...
For JavaScript (or other languages with strange Modulus) use:
if (a == b) ties++;
else if ((a - b + 3) % 3 == 1) wins++;
else losses++;
A 3x3 matrix would be "more elegant", I suppose.
char result = "TWLLTWWLT".charAt(a * 3 + b);
(Edited: Forgot that a and b were already zero-origin.)
I suppose you could use the terniary operator like this -
if (b==0) a==1? wins++ : loss++;
if (b==1) a==1? loss++ : wins++;
if (b==2) a==1? loss++ : wins++;
You can do it with a simple mathematical formula to get the result and then compare with if like this:
var moves = {
'rock': 0,
'paper': 1,
'scissors': 2
};
var result = {
'wins': 0,
'losses': 0,
'ties': 0
};
var processMove = function (a, b) {
var processResult = (3 + b - a) % 3;
if (!processResult) {
++result['ties'];
} else if(1 == processResult) {
++result['losses'];
} else {
++result['wins'];
}
return result;
};
jsFiddle Demo
One line processMove function without return:
var processMove = function (a, b) {
((3 + b - a) % 3) ? 1 == ((3 + b - a) % 3) ? ++result.losses : ++result.wins : ++result.ties;
};
how do you do it in java?
result = (comp - x ) % 3 ;
System.out.println (result);
if (result == 0 )// if the game is tie
{
System.out.println ("A Tie!") ;
}
else if (result == 1 || result == 2 )
{
//System.out.println (user + " " + "beats" + " " + computer_choice + " you win" );
System.out.println ("comp win");
}
else
{
System.out.println ("you win");
//System.out.println (computer_choice + " " + "beats" + " " + user + "you lose");
}