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 (2057B)


      1import sys
      2sys.path.append("../common")
      3import aoc
      4
      5gridserial = int(aoc.data)
      6
      7# rack ID = x + 10
      8# intial power = rackID * y
      9# power += gridserial
     10# power *= rackID
     11# power = str(power)[2]
     12# power -= 5
     13
     14def get_power(x,y):
     15    id = x + 10
     16    power = id * y
     17    power += gridserial
     18    power *= id
     19    spower = str(power)
     20    if len(spower) > 2:
     21        power = int(spower[-3])
     22    else:
     23        power = 0
     24    power -= 5
     25    return power
     26
     27def solve1(args):
     28    maxpower = None
     29    coords = None
     30    for x in range(300-2):
     31        for y in range(300-2):
     32            power = 0;
     33            for i in range(3):
     34                for j in range(3):
     35                    power += get_power(x+i,y+j)
     36            if maxpower == None or power > maxpower:
     37                maxpower = power
     38                coords = (x, y)
     39
     40    return f"{coords[0]},{coords[1]}"
     41
     42def gen_map():
     43    vmap = [[0 for y in range(300)] for x in range(300)]
     44    for x in range(300):
     45        for y in range(300):
     46            vmap[x][y] = get_power(x,y)
     47    return vmap
     48
     49def solve2(args):
     50    maxpower = None
     51    res = None
     52    pmap = gen_map()
     53    vmap = [[list() for y in range(300)] for x in range(300)]
     54    for s in range(1, 301):
     55        aoc.debug(f"\rTrying: {s}", end="")
     56        cmaxpower = None
     57        cres = None
     58        for x in range(300-(s-1)):
     59            for y in range(300-(s-1)):
     60                vmap[x][y] += [pmap[x+(s-1)][y+i] for i in range(s)]
     61                vmap[x][y] += [pmap[x+i][y+(s-1)] for i in range(s-1)]
     62                power = sum(vmap[x][y]);
     63                if cmaxpower == None or power > cmaxpower:
     64                    cmaxpower = power
     65                    cres = (x, y, s)
     66        if maxpower == None or cmaxpower > maxpower:
     67            maxpower = cmaxpower
     68            res = cres
     69        elif cmaxpower < maxpower:
     70            break
     71
     72    aoc.debug("\r" + " " * 50 + "\r", end="")
     73
     74    return f"{res[0]},{res[1]},{res[2]}"
     75
     76aoc.run(solve1, solve2, sols=["21,93", "231,108,14"])