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.

Add solution for 2016/18

+55
+52
2016/day18.py
··· 1 + import fileinput 2 + 3 + 4 + def is_safe(row, x): 5 + """Helper function to read out-of-bounds tiles as safe.""" 6 + if x < 0 or x >= len(row): 7 + return True 8 + 9 + return row[x] 10 + 11 + 12 + def predict_next_row(row): 13 + """Given a row, returns the predicted following row.""" 14 + next_row = [] 15 + 16 + for i in range(len(row)): 17 + a, b, c = (is_safe(row, x) for x in range(i-1, i+2)) 18 + next_row.append(predict_safe(a, b, c)) 19 + 20 + return tuple(next_row) 21 + 22 + 23 + def predict_safe(a, b, c): 24 + if a and b and not c: 25 + return False 26 + elif not a and b and c: 27 + return False 28 + elif a and not b and not c: 29 + return False 30 + elif not a and not b and c: 31 + return False 32 + 33 + return True 34 + 35 + 36 + if __name__ == '__main__': 37 + # Represent safe tiles as True and traps as False 38 + raw_first_row = fileinput.input()[0].strip() 39 + row = tuple(True if c == '.' else False for c in raw_first_row) 40 + safe_tiles = sum(row) 41 + 42 + for _ in range(40 - 1): 43 + row = predict_next_row(row) 44 + safe_tiles += sum(row) 45 + 46 + print "Number of safe tiles in first 40 rows:", safe_tiles 47 + 48 + for _ in range(400000 - 40): 49 + row = predict_next_row(row) 50 + safe_tiles += sum(row) 51 + 52 + print "Number of safe tiles in all 400000 rows:", safe_tiles
+1
2016/inputs/18.txt
··· 1 + ...^^^^^..^...^...^^^^^^...^.^^^.^.^.^^.^^^.....^.^^^...^^^^^^.....^.^^...^^^^^...^.^^^.^^......^^^^
+2
2016/outputs/18.txt
··· 1 + 1982 2 + 20005203