progress

~/problems / Geometry

Which triangular pen is the sheep in?

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A farmer fences triangular pens in a field and wants to know which pen each sheep is in.

Write pen_of(pens, sheep) -> list[int]. Each pen is three integer corners ((x1, y1), (x2, y2), (x3, y3)), listed clockwise or counter-clockwise, with non-zero area; pens may overlap. For each sheep (x, y), return the smallest index of a pen containing it, or -1. A sheep on a fence (edge or corner) is inside.

pens = [((0, 0), (4, 0), (0, 4)),       # pen 0
        ((10, 0), (4, 3), (10, 6))]     # pen 1, listed clockwise
pen_of(pens, [(1, 1), (2, 2), (8, 3), (4, 3), (5, 5)])
# [0, 0, 1, 1, -1]
# (2, 2) is on pen 0's slanted fence; (4, 3) is a corner of pen 1
Two triangular pens and five sheep: (1, 1) and (2, 2) are in pen 0, with (2, 2) on its slanted fence; (8, 3) and (4, 3) are in pen 1, with (4, 3) on its corner; (5, 5) is outside both.

Up to 200 pens and 200 sheep; coordinates within ±10^9. Integers only: no floats, division or angles.

Show hint

the sign of cross(a, b, c) = (b.x - a.x)·(c.y - a.y) - (b.y - a.y)·(c.x - a.x) says which side of a→b the point c is on. A point is in a triangle (boundary included) unless it's strictly left of one edge and strictly right of another.

Topic: Geometry primitives. Cross product for orientation, segment intersection, convex hull.

0:00
Ctrl ' run · Ctrl ↵ submit
esc