17

Day 12: Garden Groups

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

you are viewing a single comment's thread
view the rest of the comments
[-] iAvicenna@lemmy.world 2 points 6 days ago* (last edited 6 days ago)

Python

Had to rely on an external polygon library for this one. Part 1 could have been easily done without it but part 2 would be diffucult (you can even use the simplify function to count the number of straight edges in internal and external boundaries modulo checking the collinearity of the start and end of the boundary)


import numpy as np
from pathlib import Path
from shapely import box, union, MultiPolygon, Polygon, MultiLineString
cwd = Path(__file__).parent

def parse_input(file_path):
  with file_path.open("r") as fp:
    garden = list(map(list, fp.read().splitlines()))

  return np.array(garden)

def get_polygon(plant, garden):
  coords = list(map(tuple, list(np.argwhere(garden==plant))))
  for indc,coord in enumerate(coords):

    box_next = box(xmin=coord[0], ymin=coord[1], xmax=coord[0]+1,
                   ymax=coord[1]+1)

    if indc==0:
      poly = box_next
    else:
      poly = union(poly, box_next)

  if isinstance(poly, Polygon):
    poly = MultiPolygon([poly])

  return poly

def are_collinear(coords, tol=None):
    coords = np.array(coords, dtype=float)
    coords -= coords[0]
    return np.linalg.matrix_rank(coords, tol=tol)==1

def simplify_boundary(boundary):

  # if the object has internal and external boundaries then split them
  # and recurse
  if isinstance(boundary, MultiLineString):
    coordinates = []
    for b in boundary.geoms:
      coordinates.append(simplify_boundary(b))
    return list(np.concat(coordinates, axis=0))

  simple_boundary = boundary.simplify(0)
  coords = [np.array(x) for x in list(simple_boundary.coords)[:-1]]
  resolved = False

  while not resolved:

    end_side=\
    np.concat([x[:,None] for x in [coords[-1], coords[0], coords[1]]], axis=1)

    if  are_collinear(end_side.T):
      coords = coords[1:]
    else:
      resolved = True

  return coords

def solve_problem(file_name):

  garden = parse_input(Path(cwd, file_name))
  unique_plants = set(garden.flatten())
  total_price = 0
  discounted_total_price = 0

  for plant in unique_plants:

    polygon = get_polygon(plant, garden)

    for geom in polygon.geoms:
      coordinates = simplify_boundary(geom.boundary)
      total_price += geom.area*geom.length
      discounted_total_price += geom.area*len(coordinates)

  return int(total_price), int(discounted_total_price)

this post was submitted on 12 Dec 2024
17 points (94.7% liked)

Advent Of Code

920 readers
52 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS