aoc-2018-python

Advent of Code 2018 Solutions in Python
git clone https://git.sinitax.com/sinitax/aoc-2018-python
Log | Files | Refs | README | sfeed.txt

solve.py (1926B)


      1import sys
      2sys.path.append("../common")
      3import aoc
      4
      5data = [[int(v) for v in l.split(",")] for l in aoc.data.split("\n")]
      6
      7minx = min(data, key = lambda x: x[0])[0]
      8maxx = max(data, key = lambda x: x[0])[0]
      9miny = min(data, key = lambda x: x[1])[1]
     10maxy = max(data, key = lambda x: x[1])[1]
     11
     12def closest(x, y):
     13    mc = None
     14    md = None
     15    ad = None
     16    for i in range(len(data)):
     17        c = data[i]
     18        dist = abs(c[0] - x) + abs(c[1] - y)
     19        if md == None or dist < md:
     20            md = dist
     21            mc = i
     22            ad = None
     23        elif dist == md:
     24            ad = dist
     25    return mc, ad
     26
     27def combined_dist(x, y):
     28    dist = 0
     29    for i in range(len(data)):
     30        c = data[i]
     31        dist += abs(c[0] - x) + abs(c[1] - y)
     32    return dist
     33
     34def solve1(args):
     35    areas = dict()
     36    for x in range(minx, maxx):
     37        for y in range(miny, maxy):
     38            mc, ad = closest(x, y)
     39            if ad == None:
     40                if mc not in areas:
     41                    areas[mc] = 1
     42                else:
     43                    areas[mc] += 1
     44
     45    # remove outside points
     46    for i in range(len(data)):
     47        c = data[i]
     48        mc, ac = closest(minx, c[1])
     49        if mc == i:
     50            areas.pop(i)
     51            continue
     52        mc, ac = closest(maxx, c[1])
     53        if mc == i:
     54            areas.pop(i)
     55            continue
     56        mc, ac = closest(c[0], miny)
     57        if mc == i:
     58            areas.pop(i)
     59            continue
     60        mc, ac = closest(c[0], maxy)
     61        if mc == i:
     62            areas.pop(i)
     63            continue
     64
     65    return max(areas.values())
     66
     67def solve2(args):
     68    safezone = 0
     69    for x in range(minx, maxx):
     70        for y in range(miny, maxy):
     71            dist = combined_dist(x,y)
     72            if dist < 10000:
     73                safezone += 1
     74    return safezone
     75
     76aoc.run(solve1, solve2, sols=[3276, 38380])