progress

~/problems / Geometry

Polygon area with the shoelace formula

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

easy basics ~10 min

A simple polygon is given by its integer corners (x, y) in order; the last connects back to the first.

Write doubled_signed_area(poly: list[tuple[int, int]]) -> int returning twice the signed area: positive for counter-clockwise corners, negative for clockwise. Twice the area is always an integer here, so no floats.

The shoelace formula sums cross products of consecutive corners, wrapping around:

2 · area = Σ (x_i · y_{i+1} − x_{i+1} · y_i)      with index i+1 taken mod n
doubled_signed_area([(0, 0), (4, 0), (4, 3), (0, 3)])   # 24   (4x3 rectangle, counter-clockwise)
doubled_signed_area([(0, 0), (0, 3), (4, 3), (4, 0)])   # -24  (same rectangle, clockwise)
doubled_signed_area([(0, 0), (1, 0), (0, 1)])           # 1    (triangle of area 1/2)

Fewer than 3 corners, or all collinear, gives 0. Up to 10^5 corners; coordinates within ±10^9.

Show hint

loop over zip(poly, poly[1:] + poly[:1]), adding x1 * y2 - x2 * y1; don't forget the closing edge.

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

0:00
Ctrl ' run · Ctrl ↵ submit
esc