Question

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.

Était-ce utile?

La solution

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);     
}

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top