From b9ec10d7aef4ae145e1200899376bdb4d22e8491 Mon Sep 17 00:00:00 2001 From: Simmo Saan Date: Sun, 10 Dec 2023 12:35:51 +0200 Subject: [PATCH] Extract Geometry.polygonArea to library --- .../eu/sim642/adventofcode2023/Day10.scala | 12 ++---------- .../eu/sim642/adventofcodelib/Geometry.scala | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 10 deletions(-) create mode 100644 src/main/scala/eu/sim642/adventofcodelib/Geometry.scala diff --git a/src/main/scala/eu/sim642/adventofcode2023/Day10.scala b/src/main/scala/eu/sim642/adventofcode2023/Day10.scala index 3f277278..8a69f9ed 100644 --- a/src/main/scala/eu/sim642/adventofcode2023/Day10.scala +++ b/src/main/scala/eu/sim642/adventofcode2023/Day10.scala @@ -1,6 +1,6 @@ package eu.sim642.adventofcode2023 -import eu.sim642.adventofcodelib.Grid +import eu.sim642.adventofcodelib.{Geometry, Grid} import eu.sim642.adventofcodelib.GridImplicits.* import eu.sim642.adventofcodelib.IteratorImplicits.* import eu.sim642.adventofcodelib.graph.{BFS, Distances, GraphTraversal, UnitNeighbors} @@ -97,7 +97,6 @@ object Day10 { /** * Solution, which calculates inside points using Pick's theorem. * Area of the polygon is calculated using the shoelace formula. - * @see [[https://en.wikipedia.org/wiki/Shoelace_formula]] * @see [[https://en.wikipedia.org/wiki/Pick%27s_theorem]] */ object PicksTheoremPart2Solution extends Part2Solution { @@ -128,14 +127,7 @@ object Day10 { val loop = dfs(grid.posOf('S'), Set.empty, Nil) - val area = { - ((loop.last :: loop).iterator - .zipWithTail - .map(_ cross _) - .sum / 2).abs - } - - area - loop.size / 2 + 1 + Geometry.polygonArea(loop) - loop.size / 2 + 1 } } diff --git a/src/main/scala/eu/sim642/adventofcodelib/Geometry.scala b/src/main/scala/eu/sim642/adventofcodelib/Geometry.scala new file mode 100644 index 00000000..a3f82be9 --- /dev/null +++ b/src/main/scala/eu/sim642/adventofcodelib/Geometry.scala @@ -0,0 +1,18 @@ +package eu.sim642.adventofcodelib + +import eu.sim642.adventofcodelib.IteratorImplicits.* +import eu.sim642.adventofcodelib.pos.Pos + +object Geometry { + + /** + * Calculates the area of a simple polygon using the shoelace formula. + * @see [[https://en.wikipedia.org/wiki/Shoelace_formula]] + */ + def polygonArea(poss: Seq[Pos]): Int = { + ((poss.last +: poss).iterator + .zipWithTail + .map(_ cross _) + .sum / 2).abs + } +}