I have an argument with my friend because I don't think fib_2() is recursion, but he says it is because it calls itself.
I don't think it is because one fib_2() doesn't have a return result for use as an argument for another fib_2().
I think fib_2() is the same with fib_3(),it's a iteration,not a recursion.
So is it a recursion or not ?
public class Demo {
public static void main(String[] args) {
System.out.printf("fib_1 -> %d\n", fib_1(10));
System.out.printf("fib_2 -> %d\n", fff(10));
System.out.printf("fib_3 -> %d\n", fib_3(10));
}
//This is recursion
public static int fib_1(int n) {
if (n == 1 || n == 2)
return 1;
return fib_1(n - 1) + fib_1(n - 2);
}
//Is this recursion or not ?
public static int fff(int n) {
int a = 1, b = 1, c = 0, count = 2;
return fib_2(a, b, n, c, count);
}
public static int fib_2(int a, int b, int n, int c, int count) {
if (count == n) {
return c;
}
int tmp = b;
b = a + b;
a = tmp;
c = b;
++count;
return fib_2(a, b, n, c, count);
}
public static int fib_3(int n) {
int a = 1, b = 1;
for (int i = 2; i < n; i++) {
int temp = b;
b = a + b;
a = temp;
}
return b;
}
}
fff is not recursive, because it does not calls itself. It calls fib_2 which has a recursive implementation, but it is not enough to make the fff method recursive.
fib_2, on the other hand, is textbook-recursive: it has a base case for count == n, and it has a recursive branch that calls fib_2 with new values of a, b, and c.
fib_2 is recursive. fff is not.
The first call of fib_2 uses returns (hence 'uses') the result of the second call.
Or formal:
Recursion is defined by two properties:
A simple base case (or cases)—a terminating scenario that does not use recursion to produce an answer
A set of rules that reduce all other cases toward the base case
Your if inside fib_2 fulfills the first property.
The call to fib_2 fulfills the second.
fib_3 is an iterative.
fib_2 is not equal to fib_3!
Two functions are equal (in a mathematical manner), if and only if they produce the same output for every given input! fib_2 and fib_3 have different parameters so this can't be true.
fib_3 may be equal to fff and/or fib_1
For equality in a computer science manner you have to consider things like side effects.
public static int fib_2(int a, int b, int n, int c, int count) {
if (count == n) {
return c;
}
int tmp = b;
b = a + b;
a = tmp;
c = b;
++count;
return fib_2(a, b, n, c, count);
}
I think in this code recussion is happening.
Related
Is the following method tail-recursive?
I believe that it is not tail recursive because it relies on the previous results and so needs a stack frame, am I correct to state this?
public int[] fib(int n)
{
if(n <= 1){
return (new int[]{n,0});
}
else{
int[] F = fib(n-1);
return (new int[]{F[0]+ F[1], F[0]});
}
}
You are correct: It is not tail recursive because the last line is not of the form
return funcName(args);
Yes, you are correct, since it does not end with a call to itself of the form of
return fib(somevalue);
To convert it into a tail-recursive version you could do something like
// Tail Recursive
// Fibonacci implementation
class GFG
{
// A tail recursive function to
// calculate n th fibonacci number
static int fib(int n, int a, int b )
{
if (n == 0)
return a;
if (n == 1)
return b;
return fib(n - 1, b, a + b);
}
public static void main (String[] args)
{
int n = 9;
System.out.println("fib(" + n +") = "+
fib(n,0,1) );
}
}
Code taken from https://www.geeksforgeeks.org/tail-recursion-fibonacci/
This is the task:
Implement a static-public method named "createDouble" in the class "Functionality.java". The method gets two integer values a and b as input and should transform them to a double value and return it as follows:
The first input value a, should be placed before the comma or dot.
The second input value b, should be after the comma or dot and superfluous zeros should be removed.
No imports may be used to solve this task. Also the use of the Math library or other libraries is prohibited. Implement an algorithm that contains at least one meaningful loop.
This was my idea:
public class Functionality {
public static double createDouble(int a, int b) {
double c = b;
double d = 1;
while (c >= 1) {
c /= 10;
d *= 10;
}
return a + b/d;
}
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(createDouble(12, Integer.MAX_VALUE));
}
}
The problem is I am using the Method Integer.MAX Value which I shouldn´t use. Is there another option to write this code ?
Your code looks sound, just a small tweek I would make. Your variable c will equal what you want b to be after it's done dividing so you can just use it directly. Otherwise, you don't really need to be using Integer.MAX_VALUE at all. Just use arbitrary values.
public class Functionality
{
public static double createDouble(int a, int b) {
double c = b;
while(c >= 1)
c /= 10;
return a + c;
}
public static void main(String[] args) {
System.out.println(createDouble(15, 351));
System.out.println(createDouble(32, 8452));
}
}
Output:
15.351
32.8452
Here my Implementation
public class Functionality {
private static double logb10(double num){
return (num > 1) ? 1 + logb10(num / 10) : 0;
}
public static double createOtherDouble(int a, int b) {
double c = a;
int len =(int) logb10(b);
double d = b;
for(int i = 0; i < len; i++){
d /= 10;
}
return c + d;
}
public static void main(String []args){
System.out.println(Integer.MAX_VALUE);
System.out.println(createOtherDouble(12, Integer.MAX_VALUE));
}
}
Given two stacks of non-negative integers. Compute the maximum number of integers that can be removed from the top of the stacks without exceeding the sum K. Suppose two stacks A and B are given as depicted in the below image. Then a maximum of 4 integers can be removed as depicted in the second image without exceeding the sum 10. If needed please find the source here.
I tried a DP approach to solve the problem. But I could pass only a few test cases. Can someone please tell what went wrong.
static int maxStacks(int maxSum, int[] a, int[] b) {
Stack<Integer> stackA = new Stack<>();
Stack<Integer> stackB = new Stack<>();
for(int i=a.length-1;i>=0;i--) {
stackA.push(a[i]);
}
for(int i=b.length-1;i>=0;i--) {
stackB.push(b[i]);
}
return solve(stackA, stackB, maxSum, 0);
}
static int solve(Stack<Integer> a, Stack<Integer> b, int maxSum, int currSum) {
if(a.isEmpty() && b.isEmpty()) {
return 0;
}
int ansA;
if(a.isEmpty()) {
ansA = 0;
} else {
int peek = a.peek();
if((currSum + peek) > maxSum) {
ansA = 0;
} else {
a.pop();
ansA = 1 + solve(a, b, maxSum, (currSum + peek));
}
}
int ansB;
if(b.isEmpty()) {
ansB = 0;
} else {
int peek = b.peek();
if((currSum + peek) > maxSum) {
ansB = 0;
} else {
b.pop();
ansB = 1 + solve(a, b, maxSum, (currSum + peek));
}
}
return Math.max(ansA, ansB);
}
I believe the core issue in your algorithm is coming from shallow copy of Stack. In the following code segment:
} else {
a.pop();
ansA = 1 + solve(a, b, maxSum, (currSum + peek));
}
you have already popped from stack A and so when the flow for B is executed at ansB = 1 + solve(a, b, maxSum, (currSum + peek));, instead of using original Stack A, you are infact passing on the modified Stack.
On a separate note, I believe this is not a DP solution. I would suggest you read up more on that.
I'm having some problems whit an exercise I found.
I was provided a method, and can't make any changes to it.
Inside said method, I should identify the first repeating digit, beetwen two integers, And return it's position.
For example: 1234 and 4231 results in 1.
And I managed to make it work,
It's just that it doesn't work if I try to use the method more than once, it simply keeps adding to the previous value.
This is my code so far
public static final int BASENUMERACAO = 10;
public static int indice = 0;
private static int getLowestIndexWithSameDigit(int a, int b) {
if (a < 0 || b < 0) {
throw new IllegalArgumentException("Both numbers should positive " + a + " " + b);
} else {
if (a % BASENUMERACAO == b % BASENUMERACAO) {
return indice;
} else if (a / BASENUMERACAO != 0 && b / BASENUMERACAO != 0) {
indice++;
return getLowestIndexWithSameDigit(a / BASENUMERACAO, b / BASENUMERACAO);
} else {
return -1;
}
}
I tried passing index, as a local variavel, but it just overrides the curent value, everytime it's called, therefore only returning 0 or -1
Could someone tell me how to I do keep count in a recursive method, or just how do I identify the digit whitout a counter?
The problem is that you are retaining state from the previous invocation, in the indice variable. indice is an example of mutable global state, which is generally a bad idea for the reason you are experiencing here: you might carry over the results of previous calculations into new calculations, leading to unpredictable (or maybe unexpected) results.
Make your indice variable a parameter of the method:
private static int getLowestIndexWithSameDigit(int a, int b, int indice) {
// ...
}
So your recursive call will also pass a value for this:
return getLowestIndexWithSameDigit(a / BASENUMERACAO, b / BASENUMERACAO, indice);
To start the iteration, you can either explicitly pass 0, or you can create a method which takes just a and b:
private static int getLowestIndexWithSameDigit(int a, int b) {
return getLowestIndexWithSameDigit(a, b, 0);
}
Create another method to call your recursive method and use the vars that you need as parameter for the recursive version and keep passing them.
Something like:
private static int myMethod( int a, int b ) {
return myRecursiveMethod( a, b, 0, 0 );
}
private static int myRecursiveMethod( int a, int b, int var1, int var2 ) {
// do the recursive work...
myRecursiveMethod( newValueForA, newValueForB, var1, var2 ) {
}
I have 3 ways to swap 2 variables (basically 3 different algorithms). Since you can't pass a method as a parameter in Java, I thought this would be a good time to use lambda expressions.
chooseSwapMethod(int selection) {
if(selection == 1) {
functionThatUsesSwap(
(int[] arr, int x, int y) -> {
int holder = arr[x];
arr[x] = arr[y];
arr[y] = holder;
});
}
else if(selection == 2)
{
functionThatUsesSwap(
(int[] arr, int x, int y) -> {
arr[x] -= arr[y];
arr[y] = arr[x]-arr[y];
arr[x] -= arr[y];
});
}
else if(selection == 3) {
functionThatUsesSwap(
(int[] arr, int x, int y) -> {
arr[x] = arr[x]^arr[y];
arr[y] = arr[y]^arr[x];
arr[x] = arr[x]^arr[y];
});
}
else {
throw new IllegalArgumentEarr[x]ception();
}
}
but in the method functionThatUsesSwap how do you actually use the swap? Am I not understanding lambda expressions clearly? For example
public void functionThatUsesSwap(Swaper s)
{
int[] someArr = {1, 2};
s.doSwap(someArr, 0, 1);//this is where I’m stuck
System.out.println(“a: “+someArr[0]+” b: “+someArr[1]);//this should print out a: 2 b: 1
}
Java is pass by value, that means that in the following:
int a = 5;
int b = 6;
swap(a,b);
System.out.println(a+" "+b);
There is no way for the function swap to change value of a or b and the result will always be 5 6.
What you can do is:
pass and arrays of 2 numbers into the swap method, and swap numbers inside that array.
make a class to hold 2 numbers and pass that.
Going with possibility 2:
class Pair {
int a, b;
}
#FunctionalInterface
interface Swapper {
void swap(Pair p);
}
void main() {
Pair p = new Pair();
p.a = 5;
p.b = 6;
Swapper swapper = (v -> {
v.a ^= v.b;
v.b ^= v.a;
v.a ^= v.b;
});
swapper.swap(p);
System.out.println(p.a + " " + p.b);
}
Result: 6 5. Note that your claim that you can't pass a method as a parameter in Java isn't entirely true, since you can pass interfaces instead.
EDIT:
There is yet another approach (I haven't thought of this earlier because Interger class is immutable). You can create a mutable (= changable) object vrapper for integer value, something like:
class IntVrapper {
public int value;
}
Then your swap method could swap data between those two objects.