How to use fibonacci to calculate the various ways to domino tile? - java

(This may seem like this was already answered, but I am looking something more specific.) For schoolwork I need to write a method that calculates the different ways a rectangle can be tiled by a domino tile of 2*1. From what I can see, it would be the fibonacci numbers of the area. I wrote code that compiled in the compiler, but not sure it really makes sense and am clueless where to go from here. How would I be able to implement this better?
public static int domino(int n, int m) // the method signature is what I must use according the hw instructions
{
int area = n*m; // calculating the area of the passed in rectangle
int dominoes = area/2; // calculating how many dominos will be needed to cover the area
if (dominoes<=2) { // because fib 1 equals 1 and fib 2 equals 1
return 1;
} //also the stopping point
else {return domino(dominoes-1, 0) + domino(dominoes-2, 0);}
}
I do not need to worry about efficiency for this homework.

You are not correctly computing the Fibonacci numbers using your recursive calls. You are executing:
else {return domino(dominoes-1, 0) + domino(dominoes-2, 0);}
So essentially, in the first recursive call n == (dominoes - 1) and m == 0. This means that calculating the area always results in 0, as multiplying anything by 0 equals 0.
My advice would be to use an extra Fibonacci function like so:
public static int domino(int n, int m) {
// return the fibonacci number of the number of dominoes in the given rectangle
return fib((n * m) / 2);
}
public static int fib(int n) {
if(n <= 2)
// seed values of the fibonacci sequence
return 1;
else
return fib(n - 1) + fib(n - 2);
}

Related

Implementing N choose K recursively in Java

I am new to Java and am I trying to implement a recursive method for finding "n choose k".
However, I've run into a problem.
public class App {
public static void main(String[] args) throws Exception {
int n = 3;
int k = 2;
int result = combRecursion(n, k);
System.out.println(result);
}
private static int combRecursion(int n, int k) {
if (k == 0) {
return 1;
} else {
return (combRecursion(n - 1, k - 1) + combRecursion(n - 1, k));
}
}
Output:
many repetitions of this line:
at App.combRecursion(App.java:14)
It's possible to pick k items from the set of n items only if n is greater or equal to k.
You need to cut off fruitless branches of recursion spawn by the call combRecursion(n - 1, k) which doesn't reduce the number of item in the sample.
When you need to create a recursive method, it should always contain two parts:
Base case - that represents a set of edge-cases, trivial scenarios for which the result is known in advance. If the recursive method hits the base case (parameters passed to the method match one of the conditions of the base case), recursion terminates. In for this task, the base case will represent a situation when the source list was discovered completely and position is equal to its size (invalid index).
Recursive case - a part of a solution where recursive calls are made and where the main logic resides.
Your recursive case is correct: it spawns two recursive branches of execution (one will "pick" the current item, the second will "reject" it).
But in the base case, you've missed the scenario mentioned above, we need to address these situations:
n isn't large enough (k > n), so that is not possible to fetch k item. And the return value will be 0 (or instead of returning a value, you might throw an exception).
k == 0 result should be 1 (it's always possible to take 0 items, and there's only one way to do it - don't pick anything).
When k == n - there's only one way to construct a combination, as #akuzminykh has pointed out. And the return value will be 1
Note that because your goal is to get familiar with the recursion (I'm pretty sure that you're doing it as an exercise) there's no need to mimic the mathematical formula in your solution, use pure logic.
Here is how you can implement it:
private static int combRecursion(int n, int k) {
if (k > n) return 0; // base case - impossible to construct a combination
if (n == k || k == 0) return 1; // base case - a combination was found
// recursive case
return combRecursion(n - 1, k - 1) + combRecursion(n - 1, k);
}
main() - demo
public static void main(String[] args) {
System.out.println(combRecursion(3, 2));
System.out.println(combRecursion(5, 2));
}
Output
3 // pick 2 item from the set of 3 items
10 // pick 2 item from the set of 5 items
Your base case ought to include both n == k || k == 0 for "n choose k" to be implemented correctly. That way, both calls will eventually terminate (even though your current implementation is rather inefficient as it has exponential runtime). A better implementation would use the formula n!/k!/(n-k)! or the multiplicative formula to run in linear time:
int factorial(int n) {
int res = 1;
for (; n > 1; n--) {
res *= n;
}
return res
}
int choose(int n, int k) {
return factorial(n)/factorial(k)/factorial(n-k);
}
further optimizing this is left as an exercise to the reader (hint: a single for loop suffices).

Stack Overflow Error when trying to create an exponent calculator using recursion in java

I'm trying to make a simple calculator to practice recursion. This is my code and I'm getting a stack overflow error. I don't necessarily care about the code to make this work as I want to figure it out myself, but I'm not sure why I would get a stack over flow error for this.
Declared in my main:
int base=3,exponent=4;
My exponent method:
static int powerN(int base, int n)
{
if ( n == 0 ) return 0;
return base * powerN (1, n-(n-1));
}
You have at least three bugs I can see. x0 is one (not zero). You should handle the case of x1 (which is x). And, when you recurse you want to pass base and n - 1 (as is you are recursing on a power of 1 - which will always be one). Like,
static int powerN(int base, int n) {
if (n == 0) {
return 1;
} else if (n == 1) {
return base;
}
return base * powerN(base, n - 1);
}

Counting the minimum number of moves in Tower of Hanoi using recursion in java

I've been working on a method that returns the minimum number of moves that can be made in the Tower of Hanoi game complacently based on the number of rings. So far I have the basic code that can calculate 2^n (n being the number of rings). However, when I go to subtract 1 the method behaves as if their are no rings.
static int countHanoiMoves(int n)
{
int unSubtrctAnswer = 0;
if(n == 0)
{
return 1;
}
int halfPower = countHanoiMoves(n / 2);
if (n % 2 == 1)
{
unSubtrctAnswer = (2 * halfPower * halfPower);
}
else
{
unSubtrctAnswer = (halfPower * halfPower);
}
return unSubtrctAnswer - 1;
}
As suggested by Andreas in comments, your algorithm is not correct. The recursive solution is actually quite a bit simpler.
Consider:
To move n rings, you first need to move all of the rings on top of the bottom one (n - 1), then move the bottom one (+ 1), then move all the others back on top (n - 1 again).
So...
static int countHanoiMoves(int n) {
if (n == 0) return 0;
if (n < 0) throw new RuntimeException("What? A negative number of rings?");
// count(n-1) + 1 + count(n-1)... since we aren't actually moving
// the rings, but merely counting the number of moves, we can do
// it a little more cheaply by just multiplying by 2 rather than
// calling the recursive method twice
return 2 * countHanoiMoves(n - 1) + 1;
}
Note that you will fast overrun the limitations of int, so if you need to figure the count for a larger number of rings, changing the return type to long will buy you a little more breathing room.

Finding Geometric sum using recursion

I am trying to better understand recursion. I am writing a basic geometric series method which I know could be done easier with a loop but that is not the purpose. The method is producing the currect output for the values of 0 and 1 which is simply 1 and 1.5. But for 2 it is outputting 1.25 when it should be 1.75. Any pointers on a better way to approach this?
public static double geometricSum(int n) {
if(n == 0){
return 1;
}
n = n * 2;
return 1.0 / n + geometricSum((int) (1/Math.pow(2, n)));
}
This happens because you are casting a float into a int.
1/(2^2)=1/4=0.25 --> 0
As you are passing your float as an int you're not getting your thing working propperly.
So 0.25 + geometricSum(0)=1.25.
On the first one happens the same. you pass the 0.5, but turned into an int so you.re not getting your aproximation propperly done.
As an advice, ALWAYS put () on your math functions in order to make the program, and you yourself, understand in which order it computes the numbers.
The first problem is the cast to int, giving the wrong result, already described by reyeselda95.
There is a second problem hidden, which is that if you fix that you get this:
public static double geometricSum(double n) {
System.err.println("Calling with " + n);
if(n == 0){
return 1;
}
n = n * 2;
return 1.0 / n + geometricSum((1/Math.pow(2, n)));
}
Calling this with the provided value of 2, leads to a loop between calls with the following values, leading to a stack overflow.
...
Calling with 0.4999999999999999
Calling with 0.5000000000000001
Calling with 0.4999999999999999
Calling with 0.5000000000000001
...
This may be the function you are looking for, if I understand correctly:
public static double geometricSum(int count) {
if (count == 0) {
return 1;
}
return geometricSum(count-1) + Math.pow(2, -count);
}
Don't cast float to int;
When using float, are you sure your formula is correct? The recursion breaks if an argument is zero, but you will get StackOverflowError when passing the result of 1.0/Math.pow(2, n) to the function.
This is my python code:
def geometricSum(k):
if k == 0:
return 1
return 1/2**k + geometricSum(k-1)
k = int(input())
print(geometricSum(k))
This is all about the power of 2 i.e. 2 Pow n where n is an integer.
Here Recursion is used to get the sequence of values for n.
In my case I've to calculate the value for 1/(2 pow n).

Fibonocci Generation by Recursion

I am trying to create a method that will generate a Fibonacci sequence based on user input and calculated to the tenth number, all through recursion. (Learning recursion right now, this is one exercise).
Here is my attempted code, which I am currently struggling to make work:
//being run with fibonacci(10, 10);
//Start being the number the sequence starts with
public static int fibonacci(int start, int times)
{
if(times > 0)
{
int result = fibonacci(start - 1, times - 1) + fibonacci(start - 2, times - 1);
sequence += result;
return result;
}
System.out.println(sequence);
return start;
}
This, however, returns a large amount (I think about 40,000 numbers taking approximately 10 seconds to run to completion). Also all the numbers appear to be negative, definitely not what my aim was.
Now, on to identifying the problem: I believe the problem is that the method is calling itself twice more every single time it is called, adding up to the large amount. However, I can't think of a way around this seeing as I am trying to do it through recursion each time and I have no choice but to call it again.
As for why it is negative, I haven't a clue. I thought I was using the Fibonacci equation correctly, but obviously I am doing something incorrectly.
Could anyone help me through this please?
(True, I could easily google some code for this as I am sure it is out there, but I want to actually learn how this is done and what I am doing wrong for future reference. Better to advance as a programmer than to get the grade from copied code and move on)
I think you are a little confused here with what the Fibonacci sequence is. The formula is F(n) = F(n-1) + F(n-2). Recursion should always end at a base case which for Fibonacci is F(0) = 0 and F(1) = 1. Your method only needs one variable which is n.
Think about it this way:
public static int fibonacci(int n) {
//Insert your base cases here to terminate early
//Then process the recursive formula
return fibonacci(n - 1) + fibonacci(n - 2);
}
I think I understand what you are trying to do. You want 10 fibonacci numbers from start. Perhaps something like this will work:
public static int[] fibonacci(int start, int times)
{
return fibonacci(start, times, 0, 1, new int[times]);
}
private static int[] fibonacci(int start, int times, int a, int b, int[] answer)
{
if( start > 0 )
return fibonacci(start-1, times, b, a+b, answer);
if( times > 0 )
{
answer[answer.length - times] = a;
return fibonacci(start, times-1, b, a+b, answer);
}
return answer;
}
public static void main(String[] args) {
int[] a = fibonacci(5, 10);
for(int i=0; i<a.length; i++)
{
System.out.println(a[i]);
}
}

Categories

Resources