Calculating a recurrence function in Java - java

I need to solve this recurrence function: f(n) = 5*f(n-1) - 2*f(n-2), with f(0)=1 and f(1)=2. I wrote the below code, but it is not giving the correct answer -- it outputs 164, for example, when n = 4, although the correct answer is 26 (assuming I did my math correctly).
public static int recurFunction(int n) {
if(n == 0) {
return 1;
} else if(n == 1) {
return 2;
} else {
n = ((5 * recurFunction(n - 1)) - (2 * recurFunction(n - 2)));
return n;
}
}

Your math is wrong :)
f(n) = 5*f(n-1) - 2*f(n-2)
f(0) = 1
f(1) = 2
f(2) = 5 * f(1) - 2 * f(0) = 5 * 2 - 2 * 1 = 10 - 2 = 8
f(3) = 5 * f(2) - 2 * f(1) = 5 * 8 - 2 * 2 = 40 - 4 = 36
f(4) = 5 * f(3) - 2 * f(2) = 5 * 36 - 2 * 8 = 180 - 16 = 164

It looks like your Java code is correct, but your own math is incorrect.
f(2) = 5f(1) - 2f(0) = 5 * 2 - 2 * 1 = 10 - 2 = 8
f(3) = 5f(2) - 2f(1) = 5 * 8 - 2 * 2 = 40 - 4 = 36
f(4) = 5f(3) - 2f(2) = 5 * 36 - 2 * 8 = 180 - 16 = 164

Related

Factorial Recursion, answer doesn't make sense on paper?

So I was on codingbat doing recursion excercises and I ran into this
public int factorial(int n) {
if (n == 1) {
return 1;
}
return n * factorial(n-1);
}
I don't understand how this works on paper. as 1 returns 1 thats fine, 2 returns 2, thats fine, 3 returns 6 thats fine, but then factorial(4) returns 24? factorial(5) returns 120?
It doesn't make sense because it is doing it from the last answer of n I assume but not minusing 1? But passes all the tests. So it does 6*4 = 24, rather than 4x(n-1) which wouldn't equal 24? Help?
For any factorial(n), it is computed as n x (n-1) x (n-2) x ... x 1
So for factorial(4) that will be 4 x 3 x 2 x 1 = 24
Recursion is mostly introduced using factorial as an example, so to visualize it will look like
fact(4) = 4 x fact(3)
= 4 x 3 x fact(2)
= 4 x 3 x 2 x fact(1)
= 4 x 3 x 2 x 1 = 24
The recursion repeats until it hits the "anchor" which is the base case of 1
When you're trying to understand recursion, it's good to picture a stack. Every time we're calling return n * factorial(n - 1) we are pushing a value down the stack so we can retrieve it after we're done computing the factorial(n - 1) call. And so on so forth.
factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 *factorial(1)
= 5 * 4 * 3 * 2 * 1
= 120

How to associate file number with coordinate information in a matrix?

I have a image raster of dimensions width = 155 and height = 175. Each pixel coordinate is associated with a number, meaning (1,1) is 1, (1,155) is 155 and (175,155) is 27125. Given a number, how can I find the coordinate (x,y)? I am working in Java.
Smaller matrix width = 3 height = 4
1 2 3
1,1 1,2 1,3
4 5 6
2,1 2,2 2,3
7 8 9
3,1 3,2 3,3
10 11 12
4,1 4,2 4,3
Something like that should work:
private int X_SIZE = 155;
public int getX(int position) {
return position % X_SIZE; // Starts from 0
}
public int getY(int position) {
return position / X_SIZE; // starts from 0
}
Where 155 is the dimension of the x size.
Imagine to have a matrix 3 x 5. X_SIZE is 3.
Here is the matrix population
X
Y 0 1 2
----------------
0 | 0 1 2
1 | 3 4 5
2 | 6 7 8
3 | 9 10 11
4 |12 13 14
And here are some values:
getX(0) = 0 % 3 = 0
getY(0) = 0 / 3 = 0
getX(1) = 1 % 3 = 1
getY(1) = 1 / 3 = 0
getX(8) = 8 % 3 = 2
getY(8) = 8 / 3 = 2
getX(12) = 12 % 3 = 0
getY(12) = 12 / 3 = 4
This work is you use a 0 based x and y calculation and starts from 0 to populate the array.
To have a 1 based for x and y and starting from 1 to populate the array you need to change the functions as follow:
private int X_SIZE = 155;
public int getX(int position) {
return (position - 1) % X_SIZE + 1; // Starts from 1
}
public int getY(int position) {
return (position - 1) / X_SIZE + 1; // starts from 1
}
Here are the same example as before:
X
Y 1 2 3
----------------
1 | 1 2 3
2 | 4 5 6
3 | 7 8 9
4 |10 11 12
5 |13 14 15
And here are some values:
getX(1) = (1 - 1) % 3 + 1 = 1
getY(1) = (1 - 1) / 3 + 1 = 1
getX(2) = (2 - 1) % 3 + 1 = 2
getY(2) = (2 - 1) / 3 + 1 = 1
getX(9) = (9 - 1) % 3 + 1 = 3
getY(9) = (9 - 1) / 3 + 1 = 3
getX(13) = (13 - 1) % 3 + 1 = 1
getY(13) = (13 - 1) / 3 + 1 = 5

Generate all combinations of mathematical expressions that add to target (Java homework/interview)

I've tried to solve the problem below for a coding challenge but could not finish it in 1 hour. I have an idea on how the algorithm works but I'm not quite sure how to best implement it. I have my code and problem below.
The first 12 digits of pi are 314159265358.
We can make these digits into an expression evaluating to 27182 (first 5 digits of e)
as follows:
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182
or
3 + 1 - 415 * 92 + 65358 = 27182
Notice that the order of the input digits is not changed. Operators (+,-,/, or *) are simply inserted to create the expression.
Write a function to take a list of numbers and a target, and return all the ways that those numbers can be formed into expressions evaluating to the target
For example:
f("314159265358", 27182) should print:
3 + 1 - 415 * 92 + 65358 = 27182
3 * 1 + 4 * 159 + 26535 + 8 = 27182
3 / 1 + 4 * 159 + 26535 + 8 = 27182
3 * 14 * 15 + 9 + 26535 + 8 = 27182
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182
This problem is difficult since you can have any combination of numbers and you don't consider one number at a time. I wasn't sure how to do the combinations and recursion for that step. Notice that parentheses are not provided in the solution, however order of operations is preserved.
My goal is to start off with say
{"3"}
then
{"31", "3+1", "3-1", "3*1" "3/1"}
then
{"314", "31+4", "3+1+4", "3-1-4", "31/4", "31*4", "31-4"} etc.
then look at the every value in the list each time and see if it is target value. If it is, add that string to result list.
Here is my code
public static List<String> combinations(String nums, int target)
{
List<String> tempResultList = new ArrayList<String>();
List<String> realResultList = new ArrayList<String>();
String originalNum = Character.toString(nums.charAt(0));
for (int i = 0; i < nums.length(); i++)
{
if (i > 0)
{
originalNum += nums.charAt(i); //start off with a new number to decompose
}
tempResultList.add(originalNum);
char[] originalNumCharArray = originalNum.toCharArray();
for (int j = 0; j < originalNumCharArray.length; j++)
{
//go through every character to find the combinations?
// maybe recursion here instead of iterative would be easier...
}
for (String s : tempResultList)
{
//try to evaluate
int temp = 0;
if (s.contains("*") || s.contains("/") || s.contains("+") || s.contains("-"))
{
//evaluate expression
} else {
//just a number
}
if (temp == target)
{
realResultList.add(s);
}
}
tempResultList.clear();
}
return realResultList;
}
Could someone help with this problem? Looking for an answer with coding in it, since I need help with the generation of possibilities
I don't think it's necessary to build a tree, you should be able to calculate as you go -- you just need to delay additions and subtractions slightly in order to be able take the precedence into account correctly:
static void check(double sum, double previous, String digits, double target, String expr) {
if (digits.length() == 0) {
if (sum + previous == target) {
System.out.println(expr + " = " + target);
}
} else {
for (int i = 1; i <= digits.length(); i++) {
double current = Double.parseDouble(digits.substring(0, i));
String remaining = digits.substring(i);
check(sum + previous, current, remaining, target, expr + " + " + current);
check(sum, previous * current, remaining, target, expr + " * " + current);
check(sum, previous / current, remaining, target, expr + " / " + current);
check(sum + previous, -current, remaining, target, expr + " - " + current);
}
}
}
static void f(String digits, double target) {
for (int i = 1; i <= digits.length(); i++) {
String current = digits.substring(0, i);
check(0, Double.parseDouble(current), digits.substring(i), target, current);
}
}
First, you need a method where you can input the expression
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8
and get the answer:
27182
Next, you need to create a tree structure. Your first and second levels are complete.
3
31, 3 + 1, 3 - 1, 3 * 1, 3 / 1
Your third level lacks a few expressions.
31 -> 314, 31 + 4, 31 - 4, 31 * 4, 31 / 4
3 + 1 -> 3 + 14, 3 + 1 + 4, 3 + 1 - 4, 3 + 1 * 4, 3 + 1 / 4
3 - 1 -> 3 - 14, 3 - 1 + 4, 3 - 1 - 4, 3 - 1 * 4, 3 - 1 / 4
3 * 1 -> 3 * 14, 3 * 1 + 4, 3 * 1 - 4, 3 * 1 * 4, 3 * 1 / 4
3 / 1 -> 3 / 14, 3 / 1 + 4, 3 / 1 - 4, 3 / 1 * 4, 3 / 1 / 4
You can stop adding leaves to a branch of the tree when a division yields a non integer.
As you can see, the number of leaves at each level of your tree is going to increase at a rapid rate.
For each leaf, you have to append the next value, the next value added, subtracted, multiplied, and divided. As a final example, here are 5 of the fourth level leaves:
3 * 1 + 4 -> 3 * 1 + 41, 3 * 1 + 4 + 1, 3 * 1 + 4 - 1, 3 * 1 + 4 * 1,
3 * 1 + 4 / 1
Your code has to generate 5 expression leaves for each leaf until you've used all of the input digits.
When you've used all of the input digits, check each leaf equation to see if it equals the value.
My Javascript implementation:
Will improve the code using web worker later on
// was not allowed to use eval , so this is my replacement for the eval function.
function evaluate(expr) {
return new Function('return '+expr)();
}
function calc(expr,input,target) {
if (input.length==1) {
// I'm not allowed to use eval, so I will use my function evaluate
//if (eval(expr+input)==target) console.log(expr+input+"="+target);
if (evaluate(expr+input)==target) document.body.innerHTML+=expr+input+"="+target+"<br>";
}
else {
for(var i=1;i<=input.length;i++) {
var left=input.substring(0,i);
var right=input.substring(i);
['+','-','*','/'].forEach(function(oper) {
calc(expr+left+oper,right,target);
},this);
}
}
};
function f(input,total) {
calc("",input,total);
}

Algorithm for column, row from index?

Say I have an index 12 (12th element) going from left to right, top to bottom.
I have an array[4][4].
What would be the fastest way to compute the index [3][2] given the 1D index 12? (1D index starts at 1).
Thanks
Don't know if this is fastest, but it's definitely simple:
Assuming array[x][y]
ix = floor(index / y)
iy = index % y
Example:
01
23
45
x = 3
y = 2
index = 3
ix = floor(3 / 2) = 1
iy = 3 % 2 = 1
index = 5
ix = floor(5 / 2) = 2
iy = 5 % 2 = 1
given a[x][y] is the array
use this formula
[index of 1d array]= (rnum * colsize) + (colnum + 1)
so for a[3][2] with colsize=4
= (3 * 4) + (2 + 1)
= 15

Combinations function in Java

In one of the examples in my book it creates two methods. One called combinations and one called factorial. The body on the combinations method contains the following code
private int combinations(int n, int k){
return factorial(n) / (factorial (k) * factorial (n-k));
}
In an example of actually seeing how the math works out for this formula the textbook gives the following example. With n = 5 and k = 2. It gives the following steps and says you should get 10. I'm having difficulty understating the logic.
Does ! have a special meaning in this case? How does 5! = 120 and how does !2 x !3 = 2 x 6?
C (n,k) = n!
_________
k! x (n - k)!
C (5,2) = 5!
___________
2! x !3
= 120
_________
2 x 6
= 10
n! means factorial(n). It is equal to: -
n! = n * (n - 1) * (n - 2) * .... * 1
So,
5! = 5 * 4 * 3 * 2 * 1 = 120
And !3 is rather a typo in your book. It doesn't represent a factorial
! denotes a factorial.
5! = 120
because
5! = 5 * 4 * 3 * 2 * 1
and
2! x 3! = 2 * 6
because
2! x 3! = (2 * 1) * (3 * 2 * 1)
Factorial
The ! (factorial) symbol means the product of all integers up to and including the number. So, for example:
5! = 5 * 4 * 3 * 2 * 1 = 120
This should help clarify what the factorial(int) method is doing.
By the way, if your book actually printed "!3" instead of "3!", it's a typo.

Categories