1

I recently was asked to come up with an algorithm to find all the lines for the given set of points that have more than two points on them. For instance if I have:

[(0, 0), (1, 1), (0, 2), (1, 2), (2, 2)]

I need to find all the lines that I can create with these points that includes at least three of them.

I started by finding all the pair combination of points, which is 10 different combinations. Then iterate through each pair, find the slope and y-intercept and then check the remaining points to see if they fit the equation. Or in case of slope = inf, I would just check the X value.

Just wanna know if this, brute force, is the only way or is there any other magic I could use in terms of efficiency.

Sam R.
  • 145
  • Have you efficiency considerations ? Must your algorithm have algorithmic efficiency less than $O(n^3)$ for example ? Remark: the best tag would be "Computational Geometry" but it does not exist... – Jean Marie Jun 07 '16 at 14:37
  • 1
    This answer might be useful: http://math.stackexchange.com/a/405981/137524 – Semiclassical Jun 07 '16 at 14:38
  • @JeanMarie, I personally don't have any consideration but since they asked for the efficient solution I was wondering if I provided one or failed to do so. – Sam R. Jun 07 '16 at 14:40
  • @Semiclassical, those are very good answers and more straightforward in terms of the condition checking but the complexity is the same. Thanks. – Sam R. Jun 07 '16 at 14:42

1 Answers1

1

The most efficient in terms of short coding is as follows. Constitute this large array:

$$\begin{bmatrix}x_1&x_2&\cdots &x_n\\y_1&y_2&\cdots &y_n\\1&1&\cdots &1\end{bmatrix}$$

and compute all the determinants of all $3 \times 3$ submatrices: those with a zero determinant correspond to aligned points.

This is due to the fact (signaled by @semiclassical) that the determinant

$$\begin{vmatrix}x_i&x_j&x_k\\y_i&y_j&y_k\\1&1&1\end{vmatrix}$$

is twice the area of triangle $M_iM_jM_k$, thus null if and only if the triangle is flat, i.e., iff its vertices are aligned.

Remark: It is evidently an $O(n^3)$ algorithm...

(3 nested loops : for $i=1 \cdots (n-2)$, for $j=(i+1) \cdots (n-1)$, for $k=(j+1) \cdots n$).

Jean Marie
  • 81,803