Skip to content

Commit

Permalink
Extract Geometry.polygonArea to library
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 10, 2023
1 parent b6f2d13 commit b9ec10d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
12 changes: 2 additions & 10 deletions src/main/scala/eu/sim642/adventofcode2023/Day10.scala
Original file line number Diff line number Diff line change
@@ -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}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
}

Expand Down
18 changes: 18 additions & 0 deletions src/main/scala/eu/sim642/adventofcodelib/Geometry.scala
Original file line number Diff line number Diff line change
@@ -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
}
}

0 comments on commit b9ec10d

Please sign in to comment.