let input = [
[[1, 4], [40, 4]],
[[1, 5], [40, 5]],
[[4, 7], [4, 24]],
[[1, 9], [4, 1]],
[[1, 2], [6, 4]],
[[80, 4], [90, 4]],
[[4, 1], [4, 40]],
[[4, 35], [4, 29]],
[[4, 28], [4, 35]],
[[5, 3.6], [9, 5.2]],
]; // Input
Output = [
[[[1, 4], [40, 4]], [[80, 4], [90, 4]]],
[[[1, 5], [40, 5]]],
[[[4, 7], [4, 24]], [[4, 1], [4, 40]]],
[[[4, 35], [4, 29]], [[4, 28], [4, 35]]],
[[[1, 9], [4, 1]]],
[[[1, 2], [6, 4]], [[5, 3.6], [9, 5.2]]],
];
If given an input of series of each start and end coordinates of a line, for example, [[1,4],[40,4]] means that it has 2 points connecting [1,4] and [40,4] to form a straight line. My objective now is to group all those lines which share the same equation y=mx+c, together into a nested array as shown above. For example,
[[1,4],[40,4]] and [[80,4],[90,4]] share the same linear equation y=4
[[4,7],[4,24]],[[4,1],[4,40]] share the same linear equation x=4
[[1,2],[6,4]] and [[5,3.6],[9,5.2]] share the same linear equation y=0.4x+1.6
[[1,9],[4,1]] is alone and it has the linear equation of -2.67x+11.67
Here is my working codepen demo
I know how to code out to find those m and c in y=mx+c, but the problem is when for example,[[4,7],[4,24]] and [[4,1],[4,40]] , the m gradient becomes infinity which unsolvable.
Can anyone please guide me on this on how to get the correct output?
2
Answers
You can calculate the slope equation for each set of points and assign it to each array item, then group:
To deal with the rounding issue, you’ll have to round it:
Here’s my take at it. The strategy is to first get a description of the line for each pair of points, and then group those together into a map of maps, first keyed by slopes, and then by intercepts (either x or y, depending on if the line is vertical or not), and then extract the groups into a single array.