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 day02.py

+18 -22
+18 -22
2016/day02.py
··· 7 7 ] 8 8 9 9 KEYPAD_2 = [ 10 - [None, None, '1', None, None], 11 - [None, '2', '3', '4', None], 12 - ['5', '6', '7', '8', '9'], 13 - [None, 'A', 'B', 'C', None], 14 - [None, None, 'D', None, None], 10 + ['_', '_', '1', '_', '_'], 11 + ['_', '2', '3', '4', '_'], 12 + ['5', '6', '7', '8', '9'], 13 + ['_', 'A', 'B', 'C', '_'], 14 + ['_', '_', 'D', '_', '_'], 15 15 ] 16 16 17 17 DIRS = { 18 - 'U': lambda (x, y), keypad: move(x, y, keypad, 0, -1), 19 - 'D': lambda (x, y), keypad: move(x, y, keypad, 0, 1), 20 - 'L': lambda (x, y), keypad: move(x, y, keypad, -1, 0), 21 - 'R': lambda (x, y), keypad: move(x, y, keypad, 1, 0), 18 + 'U': (0, -1), 19 + 'D': (0, 1), 20 + 'L': (-1, 0), 21 + 'R': (1, 0), 22 22 } 23 23 24 24 25 - def move(x, y, keypad, d_x, d_y): 26 - """Returns the (x, y) coordinate after (possibly) moving""" 27 - new_x = x + d_x 28 - new_y = y + d_y 25 + def move(keypad, pos, d): 26 + """Returns the (x, y) coordinate after (possibly) moving.""" 27 + new_x = max(0, min(pos[0] + DIRS[d][0], len(keypad[0]) - 1)) 28 + new_y = max(0, min(pos[1] + DIRS[d][1], len(keypad) - 1)) 29 29 30 - if new_x < 0 or new_x >= len(keypad[0]): 31 - return (x, y) 32 - elif new_y < 0 or new_y >= len(keypad): 33 - return (x, y) 34 - elif keypad[y + d_y][x + d_x] is None: 35 - return (x, y) 30 + if keypad[new_y][new_x] == '_': 31 + return pos 36 32 else: 37 - return (x + d_x, y + d_y) 33 + return (new_x, new_y) 38 34 39 35 40 36 pos_1 = (1, 1) # start in middle ··· 45 41 46 42 for i, line in enumerate(fileinput.input()): 47 43 for c in line.strip(): 48 - pos_1 = DIRS[c](pos_1, KEYPAD_1) 49 - pos_2 = DIRS[c](pos_2, KEYPAD_2) 44 + pos_1 = move(KEYPAD_1, pos_1, c) 45 + pos_2 = move(KEYPAD_2, pos_2, c) 50 46 51 47 code_1 += KEYPAD_1[pos_1[1]][pos_1[0]] 52 48 code_2 += KEYPAD_2[pos_2[1]][pos_2[0]]