Your Ad Here
Aug 07

As most of you know, a very nice series is going on dev102.com site for a while. Instead I was following the questions; I couldn't find any time to answer them till now. Here is this week's question “Point In Polygon” and below is my answer.  

   1:  //Solution : assume we draw a line parralel to x-axis. on CheckPoints y value, 
   2:  //from left side of the polygon to the point. 
   3:  //we need to count number of the borders intersects with this new line.
   4:  //if the number of intersections is odd, the point is inside
   5:  //if even then it is outside.
   6:  Point p1, p2;
   7:  int IntersectionCount = 0;
   8:  for (int i = 1; i < Polygon.Count; i++)
   9:  {
  10:      p1 = Polygon[i - 1];
  11:      p2 = Polygon[i];
  12:      //Check to draw the line from -infinity to the CheckPoint.
  13:      if ((p1.x < CheckPoint.x) && (p2.x < CheckPoint.x))
  14:      {
  15:          //Check if any intersection
  16:          if ((p1.y <= CheckPoint.y) && (p2.y >= CheckPoint.y))
  17:  IntersectionCount++;
  18:          if ((p1.y >= CheckPoint.y) && (p2.y <= CheckPoint.y))
  19:  IntersectionCount++;
  20:      }
  21:  }
  22:  if (IntersectionCount % 2 == 0)
  23:      Console.WriteLine("Outside");
  24:  else
  25:      Console.WriteLine("Inside");

Download the source. Program.cs (2.04 kb)

Tags:

Comments

dev102.com

Posted on Monday, 11 August 2008 21:23

Pingback from dev102.com

A Programming Job Interview Challenge - The End | Dev102.com

Jack Sparrow

Posted on Thursday, 14 August 2008 16:10

Brilliant solution dude!

Add comment


(Will show your Gravatar icon)  

  Country flag


  • Comment
  • Preview
Loading



Software Blogs TopOfBlogs