Skip to content

Instantly share code, notes, and snippets.

@tomjemmett
Created December 9, 2025 08:45
Show Gist options
  • Select an option

  • Save tomjemmett/75a90ff8bfd311f173e50d7dc5f0e56c to your computer and use it in GitHub Desktop.

Select an option

Save tomjemmett/75a90ff8bfd311f173e50d7dc5f0e56c to your computer and use it in GitHub Desktop.
library(tidyverse)
library(sf)
input <- readr::read_lines("inputs/actual/09.txt")
points <- str_split(input, ",") |>
lapply(as.integer)
make_rectangle <- function(p1, p2) {
sf::st_polygon(list(rbind(
c(p1[1], p1[2]),
c(p2[1], p1[2]),
c(p2[1], p2[2]),
c(p1[1], p2[2]),
c(p1[1], p1[2])
)))
}
make_boundary <- function(points) {
sf::st_polygon(list(matrix(flatten_int(c(points, points[1])), ncol = 2, byrow = TRUE)))
}
make_all_rectangles <- function(points) {
map(
points,
\(p) {
map(
points,
\(q) {
if (p[[1]] < q[[1]] || p[[2]] < q[[2]]) {
make_rectangle(p, q)
}
}
)
}
) |>
flatten() |>
discard(is.null)
}
bounds <- make_boundary(points)
rs <- make_all_rectangles(points)
rs_sf <- sf::st_as_sf(sf::st_sfc(rs))
valid <- st_filter(rs_sf, bounds, .predicate = sf::st_within)
area <- function(geom) {
bbox <- sf::st_bbox(geom)
x <- 1 + abs(bbox$xmin - bbox$xmax)
y <- 1 + abs(bbox$ymin - bbox$ymax)
unname(x * y)
}
max(sapply(valid$x, area))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment