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.

Refactor 2017/21 solution

Use dictionary to track each grid sequence.

+18 -21
+18 -21
2017/day21.py
··· 36 36 for it in range(18): 37 37 # Build up our list of subgrids 38 38 if it % 3 == 0: 39 - GRIDS = [] 40 - ORIG_GRIDS = [] 41 - for inp in SUBGRIDS: 42 - GRIDS.append([list(inp[n:n+3]) for n in range(0, 9, 3)]) 43 - ORIG_GRIDS.append(inp) 39 + GRIDS = {} 40 + for key in SUBGRIDS: 41 + GRIDS[key] = [list(key[n:n+3]) for n in range(0, 9, 3)] 44 42 45 - NEW_GRIDS = [] 46 - for grid in GRIDS: 43 + for key, grid in GRIDS.items(): 47 44 size = len(grid) 48 45 d = 2 if size % 2 == 0 else 3 49 46 ··· 53 50 for y in range(size // d): 54 51 for x in range(size // d): 55 52 # Build the string representation of each 2x2 or 3x3 subgrid 56 - subgrid = '' 53 + subgrid = ''.join( 54 + ''.join(grid[y*d + k][x*d:(x+1)*d]) 55 + for k in range(d) 56 + ) 57 57 58 - for k in range(d): 59 - subgrid += ''.join(grid[y*d + k][x*d:(x+1)*d]) 58 + # Lookup the corresponding rule and populate the new grid 59 + rule = RULES[subgrid] 60 60 61 - # Lookup the corresponding rule and populate the new grid 62 - out = RULES[subgrid] 63 61 for ny in range(d+1): 64 62 for nx in range(d+1): 65 - new_grid[y*(d+1) + ny][x*(d+1) + nx] = out[ny*(d+1) + nx] 66 - 67 - NEW_GRIDS.append(new_grid) 63 + new_grid[y*(d+1) + ny][x*(d+1) + nx] = rule[ny*(d+1) + nx] 68 64 69 - GRIDS = NEW_GRIDS 65 + GRIDS[key] = new_grid 70 66 67 + # Print puzzle output before updating subgrid count 71 68 if it in (4, 17): 72 - num_pixels = sum(lit_pixels(g) * SUBGRIDS[ORIG_GRIDS[i]] for i, g in enumerate(GRIDS)) 73 - print "Lit pixels after {} iterations:".format(it + 1), num_pixels 69 + num_pixels = sum(lit_pixels(grid) * SUBGRIDS[key] for key, grid in GRIDS.items()) 70 + print "Lit pixels after {} iterations: {}".format(it + 1, num_pixels) 74 71 75 72 # Update the count of independent 3x3 subgrids 76 73 if it % 3 == 2: 77 74 next_subgrids = Counter() 78 - for i, grid in enumerate(GRIDS): 79 - mult = SUBGRIDS[ORIG_GRIDS[i]] 75 + for grid_key, grid in GRIDS.items(): 76 + subgrid_count = SUBGRIDS[grid_key] 80 77 for y in range(0, 9, 3): 81 78 for x in range(0, 9, 3): 82 79 key = ''.join( 83 80 ''.join(grid[y+n][x:x+3]) 84 81 for n in range(3) 85 82 ) 86 - next_subgrids[key] += mult 83 + next_subgrids[key] += subgrid_count 87 84 88 85 SUBGRIDS = next_subgrids