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

  • iAvicenna@lemmy.world
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    16 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)