Data Structures & AlgorithmsHardICPC regional · geometry

Problem: How many collinear triples of points does the 3 x 3 grid {0,1,2}^2 contain? Use the cross-product test below.

Problem: How many collinear triples of points does the 3 x 3 grid {0,1,2}^2 contain? Use the cross-product test below.
from itertools import combinations
pts = [(x, y) for x in range(3) for y in range(3)]
def col(a, b, c):
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) == 0
print(sum(1 for t in combinations(pts, 3) if col(*t)))
What is printed?
  1. A. 8
  2. B. 6
  3. C. 48
  4. D. 76

Correct answer: A. 8

Collinear triples in the 3 × 3 grid lie on 3 rows, 3 columns and 2 diagonals, so 8 of the C(9,3) = 84 triples have a zero cross product. Forgetting the diagonals gives 6, counting ordered triples gives 8 × 6 = 48, and counting non-collinear triples (triangles) gives 76.

More Coding Interview Problems questions

Exams that ask this topic