Advent of Code solutions
1use crate::pos::Position;
2
3/// Get the area of a polygon given its vertices.
4///
5/// This is the shoelace formula.
6///
7pub fn area(verts: &[Position]) -> isize {
8 verts
9 .windows(2)
10 .map(|w| ((w[0].x) * (w[1].y)) - ((w[0].y) * (w[1].x)))
11 .sum::<isize>()
12 / 2
13}
14
15/// Get the perimeter of a polygon given its vertices.
16///
17/// This is the sum of the distances between each vertex.
18///
19pub fn perimeter(verts: &[Position]) -> isize {
20 verts
21 .windows(2)
22 .map(|w| (w[0].x - w[1].x).abs() + (w[0].y - w[1].y).abs())
23 .sum::<isize>()
24}