Calculating the Maximum Number of Points Belonging to One Line from an Array of Points in C#
Given:
Array of points on a plane: points[][] Xi and Yi.
Need to find:
The maximum number of points that belong to one line.
Example:
Original array: points= [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Result: 4
Example solution, not the best, but working:
public int MaxPoints(int[][] points) {
int res = 0;
if (points.Length<3) {return points.Length;}
Dictionary<Tuple<string,int>, string> dict =new Dictionary<Tuple<string, int>, string>();
string formula = "";
decimal k1 = 0;
decimal k2 = 0;
for(int i = 0;i<points.Length-1;i++)
{
for(int k = i+1;k<points.Length;k++){
if(points[i][0]==points[k][0]){
formula = "x="+points[i][0].ToString();
} else if(points[i][1]==points[k][1]){
formula = "y="+points[i][1].ToString();
} else{
k1 = decimal.Round((decimal)(points[k][1]-points[i][1])/(points[k][0]-points[i][0]),10,MidpointRounding.ToZero);
k2 = decimal.Round((decimal)(points[i][0]*points[k][1]-points[i][1]*points[k][0])/(points[k][0]-points[i][0]),10,MidpointRounding.ToZero);
formula = "y="+k1.ToString()+"*x-"+k2.ToString();
}
if(!dict.ContainsKey(new Tuple<string, int>(formula, i))){
dict.Add(new Tuple<string, int>(formula, i),formula);
}
if(!dict.ContainsKey(new Tuple<string, int>(formula, k))){
dict.Add(new Tuple<string, int>(formula, k),formula);
}
}
}
res = dict.GroupBy(x=>x.Value).ToDictionary(grp => grp.Key, grp => grp.Count()).Max(x=> x.Value);
return res;
}
Explanation of the algorithm:
Creating a dictionary where the key is a pair [line equation + index of coordinates in the array].
Value in the dictionary will be the repeated formula.
Populate the dictionary with all possible formula variants for each pair of points.
Then, look at which formulas in the dictionary are more - this is the answer.
For the line equation, take the equation of two points:
Value in the dictionary will be the repeated formula.
Populate the dictionary with all possible formula variants for each pair of points.
Then, look at which formulas in the dictionary are more - this is the answer.
For the line equation, take the equation of two points:
And bring it to the form with two coefficients:
Y=kX+b
Where k and b are coefficients, in the code above, calculated as variables k1 and k2.
Comments (0)
No comments yet.