My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Update 2018/11 solution

Hooray for partial sums.

+24 -31
+24 -31
2018/day11.py
··· 1 1 import fileinput 2 2 3 3 4 + SIZE = 300 5 + 6 + 4 7 def power_level(x, y, serial): 5 - x += 1 6 - y += 1 7 8 rack_id = x + 10 8 9 return (((rack_id * y + serial) * rack_id // 100) % 10) - 5 9 10 10 11 11 - SERIAL = int(fileinput.input()[0]) 12 - SIZE = 300 13 - GRID = [[power_level(x, y, SERIAL) for x in range(SIZE)] for y in range(SIZE)] 12 + def power_search(partials, conv_size): 13 + best_power = 0 14 + best_x = 0 15 + best_y = 0 14 16 15 - overall_sum = 0 16 - overall_x = 0 17 - overall_y = 0 18 - overall_size = 0 17 + for y in range(1, SIZE - conv_size + 1): 18 + for x in range(1, SIZE - conv_size + 1): 19 + xx = x + conv_size 20 + yy = y + conv_size 21 + power = PARTIALS[yy][xx] + PARTIALS[y][x] - PARTIALS[y][xx] - PARTIALS[yy][x] 19 22 20 - for size in range(3, 16): # window size of 16 is good enough...right? 21 - best_sum = 0 22 - best_x = 0 23 - best_y = 0 23 + if power > best_power: 24 + best_power = power 25 + best_x = x + 1 26 + best_y = y + 1 24 27 25 - for y in range(SIZE - size): 26 - for x in range(SIZE - size): 27 - total = 0 28 - for j in range(size): 29 - for i in range(size): 30 - total += GRID[y + j][x + i] 28 + return best_power, best_x, best_y, conv_size, 31 29 32 - if total > best_sum: 33 - best_sum = total 34 - best_x = x 35 - best_y = y 36 30 37 - if size == 3: 38 - print "Coordinate of most powerful 3x3 grid: {},{}".format(best_x + 1, best_y + 1) 31 + SERIAL = int(fileinput.input()[0]) 32 + PARTIALS = [[0 for _ in range(SIZE + 1)] for _ in range(SIZE + 1)] 39 33 40 - if best_sum > overall_sum: 41 - overall_sum = best_sum 42 - overall_x = best_x 43 - overall_y = best_y 44 - overall_size = size 34 + for y in range(1, SIZE + 1): 35 + for x in range(1, SIZE + 1): 36 + PARTIALS[y][x] = power_level(x, y, SERIAL) + PARTIALS[y][x-1] + PARTIALS[y-1][x] - PARTIALS[y-1][x-1] 45 37 46 - print "Identifier of the largest total power: {},{},{}".format(overall_x + 1, overall_y + 1, overall_size) 38 + print "Coordinate of most powerful 3x3 grid: {1},{2}".format(*power_search(PARTIALS, 3)) 39 + print "Identifier of the largest total power: {1},{2},{3}".format(*max(power_search(PARTIALS, n) for n in range(1, SIZE)))