Skip to content

Instantly share code, notes, and snippets.

@PamelaM
Created December 14, 2017 15:41
Show Gist options
  • Save PamelaM/5d6dd16b509d28133204633f9e477a3e to your computer and use it in GitHub Desktop.
Save PamelaM/5d6dd16b509d28133204633f9e477a3e to your computer and use it in GitHub Desktop.
Advent of Code 2017, Day 13
INPUT = """0: 3
1: 2
2: 4
4: 6
6: 5
8: 8
10: 6
12: 4
14: 8
16: 6
18: 8
20: 8
22: 6
24: 8
26: 9
28: 12
30: 8
32: 14
34: 10
36: 12
38: 12
40: 10
42: 12
44: 12
46: 12
48: 12
50: 14
52: 12
54: 14
56: 12
60: 14
62: 12
64: 14
66: 14
68: 14
70: 14
72: 14
74: 14
78: 26
80: 18
82: 17
86: 18
88: 14
96: 18"""
TEST = """0: 3
1: 2
4: 4
6: 4"""
from collections import defaultdict
from functools import partial
def read_input(input):
ports = {}
for line in input.splitlines():
idx, depth = map(int, line.split(": "))
ports[idx] = depth
#print ports
num_ports = max(ports.keys())
return [ports.get(idx, 1) for idx in range(num_ports+1)]
def _is_scanning(depth, picosecond):
if depth == 1:
return False
else:
return (picosecond % ((depth-1) * 2)) == 0
def once_through(ports, picosecond=0, stop_if_caught=False):
tot_severity = 0
times_caught = 0
start_picosecond = picosecond
for idx, depth in enumerate(ports):
if 0:
print idx, start_picosecond, picosecond
print " ", " ".join("%5s" % d for d in ports)
print " ", " ".join("%5s" % _is_scanning(d, picosecond) for d in ports)
print
if _is_scanning(depth, picosecond):
if stop_if_caught:
if 0:
print idx, start_picosecond, picosecond, "CAUGHT"
print " ", " ".join("%5s" % d for d in ports)
print " ", " ".join("%5s" % _is_scanning(d, picosecond) for d in ports)
print
return 1, 0
else:
tot_severity += depth * idx
times_caught += 1
picosecond += 1
return times_caught, tot_severity
def part_one(input):
ports = read_input(input)
times_caught, tot_severity = once_through(ports, picosecond=0, stop_if_caught=False)
return tot_severity
print part_one(TEST)
print part_one(INPUT)
def part_two(input):
ports = read_input(input)
start_picosecond = 0
while True:
if not start_picosecond % 10000:
print start_picosecond
times_caught, tot_severity = once_through(ports, picosecond=start_picosecond, stop_if_caught=True)
if times_caught == 0:
return start_picosecond
start_picosecond += 1
return start_picosecond
print part_two(TEST)
print part_two(INPUT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment