0

i have Segment class who contain 2 sections , each section contain 2 point the X and Y coordinate.

Point class has getX() and getX() method.

public class Segment
{
    private Point pointLeft;
    private Point pointRight;
}

i want to find the overlap (is there is) between 2 sections:

public double overlap (Segment other)
{

}

how can i find it (only the X axis overlap)

the 2 sections parallel to X axis (each section has the same Y)

falukky
  • 1,099
  • 2
  • 14
  • 34
  • What do you mean by "only the X axis overlap"? And do you need the size of the overlap or another Segment defining the overlapping area? – Dmytro Shevchenko Apr 11 '12 at 15:14
  • 3
    Is this homework? It seems like a very homework-y question. If it is, it should be tagged as such. – raveturned Apr 11 '12 at 15:15
  • 1
    Very much related: http://stackoverflow.com/questions/3838329/how-can-i-check-if-two-segments-intersect – vcsjones Apr 11 '12 at 15:15
  • Also this [How do you detect where two line segments intersect?](http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect) – oleksii Apr 11 '12 at 15:17

2 Answers2

1

Two points can define a rectangle.

Are you looking for the Rectangle.Intersect method?

http://msdn.microsoft.com/en-us/library/y10fyck0.aspx

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
  • i update my question - the 2 sections parallel to X axis and the 2 sections parallel to X axis (each section has the same Y) – falukky Apr 11 '12 at 15:23
1

My understanding of your question is that you first want to project both lines on the X-axis, and then find their intersection.

enter image description here

That is, you want the length of the greyed out section on the X axis in the image above.

You'll want to do it in 4 parts, like this:

if (other.pointLeft.X <= pointLeft.X && other.pointRight.X >= pointRight.X)
    return pointRight.X - pointLeft.X;

if (pointLeft.X <= other.pointLeft.X && pointRight.X >= other.pointRight.X)
    return other.pointRight.X - other.pointLeft.X;

if (pointLeft.X <= other.pointLeft.X && pointRight.X <= other.pointRight.X)
    return pointRight.X - other.pointLeft.X;

if (pointLeft.X >= other.pointLeft.X && pointRight.X >= other.pointRight.X)
    return other.pointRight.X - pointLeft.X;

return 0;

Note, I've coded this in place, and haven't had a chance to test it. But it should give you a basic idea of what needs to be done.

K Mehta
  • 10,323
  • 4
  • 46
  • 76