Wednesday, June 12, 2013

You have a set of (x,y) corordinates - like a list of .NET Point object - that form a line when plotted on a graph. If you are given a new (x,y) co-ordinate, find if it is a point in that line. (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice
{
    class Program
    {
        static void Main(string[] args)
        {
           
            List list = new List();
            Points P1 = new Points();
            P1.x = 2;
            P1.y = 4;
            Points P2 = new Points();
            P2.x = 6;
            P2.y = 1;

            Points P3 = new Points();
            P3.x = 7;
            P3.y = 4;
            list.Add(P1);
            list.Add(P2);
            list.Add(P3);
            Points P = new Points();
            P.x = 0;
            P.y = 7;
            int slope = findSlope(list);
            int newSlope = (P.y - P2.y) / (P.x - P2.x);
            Console.WriteLine((slope == newSlope).ToString());
            Console.ReadKey();
        }

//The structure of the Points object
  public  struct Points
       {
         public int x;
          public int y;
       }
public static int findSlope(List pointsList)
        {
    //    Get the 'X' and 'Y' values of any two points

        
           int x1 = pointsList.ElementAt(0).x;
            int x2 = pointsList.ElementAt(1).x;
            int y1 = pointsList.ElementAt(0).y;
            int y2 = pointsList.ElementAt(1).y;


//The slope is calculated by dividing the difference between Y co-ordinates by the difference of 'X' co-ordinates of two points

            int slope = (y2 -y1)/(x2 -x1);
            return slope;
        }
    }
}

2 comments:

Unknown said...
This comment has been removed by the author.
Unknown said...

Nice question and nicely implemented! :)

I think you should check the denominators not become 0 when calculating the slope or you will get an overflow exception.

Just to clarify, for any 2 points on a line the slope between those 2points is always the same.
So if you want to check if another random point is also on the line then you should find the slope between that random point and any other known point on the line and if the slope is the same then it proves that the point lies on that line or an extension of that line.