How to get the difference in a point? - java

So I recently was introduced to Points in my class. Right now I am trying to find the difference of X and then the difference of Y and then add them together. I am so lost and cant quite find the right answer. What are some options for this?
Just a heads up this is using the Point class.
Better put I dont understand the Point class that I was taught in my AP Computer Science class. Not that I don't understand how to subtract x2-x1. What command would I use to accomplish this because I continue to get errors when typing x2-x1.
Heres is what I am supposed to do:
"In our case, the Manhattan distance is the sum of the absolute values of the differences in their coordinates; in other words, the difference in x plus the difference in y between the points."
Exact words from teacher.

Difference of two X points? If so, you would do X1-X2...same with Y points... Y1-Y2.
To make sure the difference is positive, you can do
Math.abs(p.X1-p.X2)
likewise...
Math.abs(p.Y1-p.Y2)
then just add them together...
Math.abs(p.X1-p.X2) + Math.abs(p.Y1-p.Y2)
After your clarifications...I have revised my answer
public int manhattanDistance(Point other){ //not sure why return an int...I think returning a double makes more sense..
int xdist = Math.abs(this.x-other.x);
int ydist = Math.abs(this.y-other.y);
return (int)xdist+ydist; //cast to int because you must return int
}
or less code version...
public int manhattanDistance(Point other){
return (int)Math.abs(this.x-other.x) + Math.abs(this.y-other.y);
}

The distance between two points (in a straight line) can be calculated as:
___________________________
/ 2 2
/ (p2x - p1x) + (p2y - p1y)
v
For example, the classic 3-4-5 triangle:
4
+---*
| /
3 | / 5
|/
*
The hypotenuse (5) can be calculated as the square root of 3 * 3 + 4 * 4.
One way you would do that with two Point objects in Java would be with:
dist = (point2.x - point1.x) * (point2.x - point1.x)
+ (point2.y - point1.y) * (point2.y - point1.y);
though you could also use Math.pow(something,2) in place of the multiplications.
If on the other hand you wanted to find the Manhattan distance (as now seems evident by the extra information added to the question), you would use something like:
mdist = Math.abs (point2.x - point1.x) + Math.abs (point2.y - point1.y);
This works out the X difference (which may be negative) then takes the absolute value of that to force it to positive. Then it does the same with the Y difference and adds them together.

Related

How to get the percentage of points or the percentage that needs to get to the next level in Java?

I have a system that "translates" points of a player to a certain level, for example:
If a player has 0-49 points it translates to level 0 and 50-299 points it translates to being at level 1 and so on..
The problem here is that I want to have the percentage of the points of the player or the percentage needed to reach the next level, better if I can have the exact percentage of the points, I would appreciate it if somebody can help me with it, please. Here is how I am "translating" the points to a certain level:
public int translatePointsToLevel(int points) {
Integer level = (int) (Math.floor(25 + Math.sqrt(625 + 100 * points)) / 100);
return level;
}
From what I can tell you want to find the number of points needed to get to one level from another level. To do this you could think of your leveling system as an algebraic function where x = points and y = level.
The function for calculating your level is y = (25 + √(625 + 100 * x)) / 100
To calculate the number of points needed for a given level you need to solve this function in terms of x.
When solved for x the function is x = 50y(2y - 1).
When you put this function into code your code for calculating the points needed for a given level is as follows.
public static int pointsNeededForLevel(int level) {
return 50 * level * (2 * level - 1);
}
If you would like to calculate the percent of the way a player is to the next level you could use the following code. The percent will be represented as a double between the values of 0 through 1. If you would like to translate this into a percent just use int percentProgress = percentOfProgressToNextLevel(currentNumberOfPoints) * 100.0.
public static double percentOfProgressToNextLevel(int currentNumberOfPoints) {
int currentLevelNeededPoints = pointsNeededForLevel(translateLevel(currentNumberOfPoints));
return (double) (currentNumberOfPoints - currentLevelNeededPoints) / (double) (pointsNeededForLevel(translateLevel(currentNumberOfPoints) + 1) - currentLevelNeededPoints);
}
If you would like to calculate the number of points needed to reach the next level you could use the following code.
public static int pointsNeededToReachNextLevel(int currentNumberOfPoints) {
return pointsNeededForLevel(translateLevel(currentNumberOfPoints) + 1) - currentNumberOfPoints;
}
You are also able to clean up your original translateLevel(int) function a little bit by writing it as follows.
public static int translateLevel(int points) {
return (int) (Math.floor(25 + Math.sqrt(625 + 100 * points)) / 100);
}
One way to do this is to have another method to translate the level to the minimum number of points, level = floor(25 + sqrt(625 + 100 * points)) / 100, so minPoints = 100 * (level - 25)^2 - 6.
Then you can calculate the amount of points to level up by taking points for level + 1 and subtracting the points for the level.

How to calculate a cubic function using the Vietea's formula in Java?

I have to write a program in which I write a,b c,d (coefficients of equation 3 degree) and as a result I should get X1, X2, X3 (solutions of equation). I have to use Viete's formulas and BigDecimal for this, because my lecturer requires it from me.
I came to the conclusion that I have to solve the following system of equations:
x1+x2+x3=-b/a
x1*x2+x1*x3+x2*x3=c/a
x1*x2*x3=-d/a
I have no idea how I can do it in Java.
I tried to use the JAMA package, but I don't think I can use it to solve such a system of equations.
How can I do that?
If you want to find the roots of a cubic polynomial in Java you can do it easily using Newton-Raphson's method.
The algorithm -
1. Input: initial x, func(x), derivFunc(x)
Output: Root of Func()
2. Compute values of func(x) and derivFunc(x) for given initial x
3. Compute h: h = func(x) / derivFunc(x)
4. While h is greater than allowed error ε
- h = func(x) / derivFunc(x)
- x = x – h
Here is a demonstration for solving the cubic equation x^3-x^2+2
class XYZ {
static final double EPSILON = 0.001;
// An example function whose solution
// is determined using Bisection Method.
// The function is x^3 - x^2 + 2
static double func(double x)
{
return x * x * x - x * x + 2;
}
// Derivative of the above function
// which is 3*x^x - 2*x
static double derivFunc(double x)
{
return 3 * x * x - 2 * x;
}
// Function to find the root
static void newtonRaphson(double x)
{
double h = func(x) / derivFunc(x);
while (Math.abs(h) >= EPSILON)
{
h = func(x) / derivFunc(x);
// x(i+1) = x(i) - f(x) / f'(x)
x = x - h;
}
System.out.print("The value of the"
+ " root is : "
+ Math.round(x * 100.0) / 100.0);
}
// Driver code
public static void main (String[] args)
{
// Initial values assumed
double x0 = -20;
newtonRaphson(x0);
}
}
Output - The value of root is : -1.00
To do it your way you have to solve a system of non-linear equations which is harder but can be done using the Newton Raphson's Multivariate method. You might want to look it up. Also note that this is an approximate method and guesses the roots after you put an initial 'guess' of your own (in this case its -20)
The Newton (Raphson, Kantorovich) method for the Viete equations gives you the (Weierstrass-)Durand-Kerner method of simultaneous root approximation. However, in the completed method you will no longer see the Viete identities, they kind of cancel out. You will need complex numbers over the demanded real numbers data type.
If you go with the simple Newton method like in the other answer, then after computing the one real root you can split off the linear factor belonging to it via the Horner-Ruffini scheme and then solve the remaining quadratic equation directly. Then you only need to consider the possible complex nature of the roots in constructing the output strings, as the real and imaginary parts have easy direct formulas.

Find a sum equal or greater than given target using only numbers from set

Example 1:
Shop selling beer, available packages are 6 and 10 units per package. Customer inputs 26 and algorithm replies 26, because 26 = 10 + 10 + 6.
Example 2:
Selling spices, available packages are 0.6, 1.5 and 3. Target value = 5. Algorithm returns value 5.1, because it is the nearest greater number than target possible to achieve with packages (3, 1.5, 0.6).
I need a Java method that will suggest that number.
Simmilar algorithm is described in Bin packing problem, but it doesn't suit me.
I tried it and when it returned me the number smaller than target I was runnig it once again with increased target number. But it is not efficient when number of packages is huge.
I need almost the same algorithm, but with the equal or greater nearest number.
Similar question: Find if a number is a possible sum of two or more numbers in a given set - python.
First let's reduce this problem to integers rather than real numbers, otherwise we won't get a fast optimal algorithm out of this. For example, let's multiply all numbers by 100 and then just round it to the next integer. So say we have item sizes x1, ..., xn and target size Y. We want to minimize the value
k1 x1 + ... + kn xn - Y
under the conditions
(1) ki is a non-positive integer for all n ≥ i ≥ 1
(2) k1 x1 + ... + kn xn - Y ≥ 0
One simple algorithm for this would be to ask a series of questions like
Can we achieve k1 x1 + ... + kn xn = Y + 0?
Can we achieve k1 x1 + ... + kn xn = Y + 1?
Can we achieve k1 x1 + ... + kn xn = Y + z?
etc. with increasing z
until we get the answer "Yes". All of these problems are instances of the Knapsack problem with the weights set equal to the values of the items. The good news is that we can solve all those at once, if we can establish an upper bound for z. It's easy to show that there is a solution with z ≤ Y, unless all the xi are larger than Y, in which case the solution is just to pick the smallest xi.
So let's use the pseudopolynomial dynamic programming approach to solve Knapsack: Let f(i,j) be 1 iif we can reach total item size j with the first i items (x1, ..., xi). We have the recurrence
f(0,0) = 1
f(0,j) = 0 for all j > 0
f(i,j) = f(i - 1, j) or f(i - 1, j - x_i) or f(i - 1, j - 2 * x_i) ...
We can solve this DP array in O(n * Y) time and O(Y) space. The result will be the first j ≥ Y with f(n, j) = 1.
There are a few technical details that are left as an exercise to the reader:
How to implement this in Java
How to reconstruct the solution if needed. This can be done in O(n) time using the DP array (but then we need O(n * Y) space to remember the whole thing).
You want to solve the integer programming problem min(ct) s.t. ct >= T, c >= 0 where T is your target weight, and c is a non-negative integer vector specifying how much of each package to purchase, and t is the vector specifying the weight of each package. You can either solve this with dynamic programming as pointed out by another answer, or, if your weights and target weight are too large then you can use general integer programming solvers, which have been highly optimized over the years to give good speed performance in practice.

Mathematical issue (Increasing and deceasing two variables inside one loop)

I have a for loop and inside that integer x will increase from 533 to 813. That means 280 increments. In side the same loop I want to decrease y's value from 300 to 200 when above happens. Which means when x is 533 y must be 300 and when x is 813 y must be 200. I know this can do by decrease y's value by 100/280 in each iteration. But both are integers.
Here are some code sample i used but it is not working.:
for(int i = 0; i < b.getSize(); i++) {
x = b.getCar(i).getPosX();
b.getCar(i).setPosX(++x);
if(x >= ((getWidth() / 2) - 140) && x < ((getWidth() / 2) + 140)){
y = b.getCar(i).getPosY();
y = (double)(y - (10.0f / 28.0f));
b.getCar(i).setPosY((int)y);
}
}
How can I possibly do this. Thanks!
There are two solutions, a simple and a complex one. The simple one:
y = yoff + (int)( (double) height * x / width )
where yoff = 300, height = -100, width = 813-533. Basically, you do a floating point operation and then you round the result.
Alternatively, the same can be done using pure integer math using the Bresenham line algorithm but that would take a lot more code.
y must be a double or a float and you need to round its value when you want to use it.
If you wanna do animation, just have a look at interpolators. You can abstract the logic of computing the values in between your extremas.
Basically at the beginning, you give your interpolator the start and end values.
Then, you give the interpolator a time and it gives you back the value between start and end for that time value.
Bonus: it will allow you to change your animation look & feel without touching the rest of the code. (what you are trying to do is in fact a linear interpolation, but it will look much nicer using a sine function for instance, or some other algorithm such as bouncing, quadratic, ...)
It looks like the logic for drawing a line. The Bresenham's algorithm should be the best option.
Keep a helping variable double dy that keeps track of the precise value for y. At each iteration, update dy using your formula, then update y by taking the rounded/truncated value of dy.
NOt sure what you like to do, but your current solution sufers from rounding of floats to integers. To avoid this, calculate with floats / doubles and convert them to integer whensetting positions.

Implement Generic Power Function Without Using Math.pow in Java

I want to write a program in java, which will perform a number raised to a power, but without using math.pow. The program should be generic to include fractions as well.
The loop increment method will increment by 1, which is okay for integers; but not fractions. Please Suggest a generic method that would be helpful to me.
First, observe that pow(a,x) = exp(x * log(a)).
You can implement your own exp() function using the Taylor series expansion for
ex:
ex = 1 + x + x2/2! + x3/3! + x4/4! + x5/5! + ...
This will work for non-integer values of x. The more terms you include, the more
accurate the result will be.
Note that by using some algebraic identities, you only need to resort to the series expansion for x in the range 0 < x < 1 . exp(int + frac) = exp(int)*exp(frac), and there's no need to use a series expansion for exp(int). (You just multiply it out,
since it's an integer power of e=2.71828...).
Similarly, you can implement log(x) using one of these series expansions:
log(1+x) = x - x2/2 + x3/3 - x4/4 + ...
or
log(1-x) = -1 * (x + x2/2 + x3/3 + x4/4 + ... )
But these series only converge for x in the interval -1 < x < 1. So for values
of a outside this range, you might have to use the identity
log(pq) = log(p) + log(q)
and do some repeated divisions by e (= 2.71828...) to bring a down into a range where
the series expansion converges. For example, if a=4, you'd have to take take x=3
to use the first formula, but 3 is outside the range of convergence. So we start
dividing out factors of e:
4/e = 1.47151...
log(4) = log(e*1.47151...) = 1 + log(1.47151...)
Now we can take x=.47151..., which is within the range of convergence, and evaluate log(1+x) using the series expansion.
Think about what a power function should do.
Mathematically: x^5 = x * x * x * x * x, or ((((x*x)*x)*x)*x)
Within your for loop, you can use the *= operator to achieve the operation that happens above.
How are you handling fractions? Java has no built-in fraction type; it stores decimals that would calculate the same way as integers (in other words, x * x works with both types). If you have a special class for fractions, your loop just needs two steps: one to multiply the numerator and one to multiply the denominator.
While reading up on powers on Wikipedia:
a^x = exp( x ln(a) ) for any real number x
Is this cheating?

Categories