def b(): grid = defaultdict(bool) for row in utils.input_lines(test=False): curr = (0, 0) cmd = '' for c in row: cmd += c if cmd in DELTAS: curr = (curr[0] + DELTAS[cmd][0], curr[1] + DELTAS[cmd][1]) cmd = '' grid[curr] = not grid[curr] print(sum([1 for v in grid.values() if v])) print('--') for round in range(100): flip = set() for c in list(grid.keys()): for adjacent in [c] + neighbors(c): colored = len([cc for cc in neighbors(adjacent) if grid[cc]]) if (grid[adjacent] and (colored == 0 or colored > 2)) or (not grid[adjacent] and colored == 2): flip.add(adjacent) for f in flip: grid[f] = not grid[f] print('Day', round + 1, ':', sum([1 for v in grid.values() if v]))
def do_part_1(test=False): lines = input_lines(5, test=test) line = lines[0].strip() # This challenge has only one line #print(len(collapse_maximally(line))) #print(len(better_collapse_maximally(line))) print(len(array_collapse_maximally(line))) return
def do_part_1(test=False): lines = input_lines(6, test=test) pts = [] for num, line in enumerate(lines): pts.append(digest_line(line, num)) xmin, ymax, xmax, ymin = bounding_box(pts) #for y in range(ymin, ymax+1): # print(''.join(str(nearest_pt((x,y), pts)) for x in range(xmin, xmax+1))) infinites = set() for y in range(ymin, ymax+1): _pt = (xmin, y) infinites.add(nearest_pt(_pt, pts)) for y in range(ymin, ymax+1): _pt = (xmax, y) infinites.add(nearest_pt(_pt, pts)) for x in range(xmin, xmax+1): _pt = (x, ymin) infinites.add(nearest_pt(_pt, pts)) for x in range(xmin, xmax+1): _pt = (x, ymax) infinites.add(nearest_pt(_pt, pts)) #print(infinites) tallies = defaultdict(int) for x in range(xmin, xmax+1): for y in range(ymin, ymax+1): _pt = (x, y) tallies[nearest_pt(_pt, pts)] += 1 finites = [value for key, value in tallies.items() if key not in infinites] print(max(finites)) return
def do_part_2(record=fabric): """ Solves part 2 """ lines = input_lines(3) for line in lines: if check_overlaps(*parse_line(line), record=record): return return
def do_part_1(): """ Solves part 1 """ digested_lines = list(map(digest_line, input_lines(2))) # Poor man's partial doubles = sum(map(lambda l: contains_nple(l, reps=2), digested_lines)) triples = sum(map(lambda l: contains_nple(l, reps=3), digested_lines)) print(doubles * triples) return doubles * triples
def do_part_1(day, test=False): lines = input_lines(day, test=test) nplayers, nmarbles = map(int, digest_line(lines[0])) scores = [0] * nplayers marble_deque = deque([0]) for marble in range(1, nmarbles): turn_score = insert_marble(marble, marble_deque) scores[marble % nplayers] += turn_score #print(marble_deque) print(max(scores)) return
def do_part_1(): """ Solve the puzzle. """ data = input_lines(1) total = 0 for line in data: val, op = interpret_line(line) total = op(total, val) print(total) return total
def do_part_2(test=False): lines = input_lines(5, test=test) line = lines[0].strip() # This challenge has only one line record = 9999999 for letter in "abcdefghijklmnopqrstuvwxyz": #irec = len(collapse_maximally(remove_pair(line, letter))) #irec = len(better_collapse_maximally(remove_pair(line, letter))) irec = len(array_collapse_maximally(remove_pair(line, letter))) if irec < record: record = irec print(record) return
def do_part_2(): """ Solves part 2 """ lines = input_lines(2) for line1 in lines: for line2 in lines: if distance(line1, line2) == 1: common = common_substring(line1, line2) print(common) return common return ""
def do_part_1(test=False, record=fabric): """ Solves part 1 """ lines = input_lines(3, test=test) for line in lines: register_rect(*parse_line(line), record=record) total = 0 for val in record.values(): if val > 1: total += 1 print(total) return total
def a(): grid = defaultdict(bool) for row in utils.input_lines(test=False): curr = (0, 0) cmd = '' for c in row: cmd += c if cmd in DELTAS: curr = (curr[0] + DELTAS[cmd][0], curr[1] + DELTAS[cmd][1]) cmd = '' grid[curr] = not grid[curr] print(sum([1 for v in grid.values() if v]))
def do_part_1(test=False): lines = input_lines(7, test=test) reqs = defaultdict(set) done = [] for line in lines: pre, task = digest_line(line) reqs[task].add(pre) available = list_available(reqs, done) while available: done += available[0] remove_pre(reqs, available[0]) available = list_available(reqs, done) print(''.join(done)) return
def do_part_1(day, test=False): LEFTPAD = 10 RIGHTPAD = 30 lines = input_lines(day, test=test) init_state, rules = initial_setup(lines) # pad the initial state init_state = '.' * LEFTPAD + init_state + '.' * RIGHTPAD print(' ' * LEFTPAD + '0') print(init_state) state = init_state for i in range(20): state = evolve_state(state, rules) print(state) print(sum_pots(state, leftpad=LEFTPAD)) return
def do_part_2(test=False): lines = input_lines(6, test=test) pts = [] for num, line in enumerate(lines): pts.append(digest_line(line, num)) xmin, ymax, xmax, ymin = bounding_box(pts) counter = 0 for x in range(xmin, xmax + 1): for y in range(ymin, ymax + 1): _pt = (x, y) total = sum(distance(_pt, q) for q in pts) if total < 10000: counter += 1 print(counter) return
def do_part_2(): """ Solve the puzzle... part 2. """ data = input_lines(1) total = 0 iters = 0 # Count iters seen = set() while iters < 10**7: # so that it doesn't accidentally run forever for line in data: iters += 1 val, op = interpret_line(line) total = op(total, val) if total in seen: print(total) return total seen.add(total) return "No repetitions found."
def do_part_2(test=False): elapsed = 0 lines = input_lines(7, test=test) reqs = defaultdict(set) done = [] time_record = 5 * [(0, '')] for line in lines: pre, task = digest_line(line) reqs[task].add(pre) available = list_available(reqs, done) go_to_work(reqs, done, available, time_record, elapsed) while available and elapsed < 10000: advance_time(time_record) time_record, reqs, done = go_to_work(reqs, done, available, time_record, elapsed) available = list_available(reqs, done) elapsed += 1 print(elapsed) return
def do_part_1(): """ Solves part 1 """ guards = defaultdict(list) lines = input_lines(4, test=False) guard, start = get_guard_number_and_start(lines[0]) falls = None for line in lines[1:]: if 'asleep' in line: falls = get_time(line) elif 'wakes' in line: if falls: wakes = get_time(line) segment = [falls, wakes] falls = None guards[guard] = guards[guard] + [segment] elif '#' in line: if falls: wakes = get_guard_number_and_start(line)[1] if wakes < falls: wakes = 60 segment = [falls, wakes] falls = None guards[guard] = guards[guard] + [segment] segments_asleep = [] guard, start = get_guard_number_and_start(line) max_time = 0 max_guard_id = "" for guard in guards: time_slept = time_sleeping(guard, guards) if time_slept >= max_time: max_time = time_slept max_guard_id = guard time = most_common_time(max_guard_id, guards)[0] print(int(max_guard_id[1:]) * int(time)) return guards
def do_part_2(day, test=False): LEFTPAD = 10 RIGHTPAD = 300 lines = input_lines(day, test=test) init_state, rules = initial_setup(lines) # pad the initial state init_state = '.' * LEFTPAD + init_state + '.' * RIGHTPAD print(' ' * LEFTPAD + '0') print(' 0', init_state[:150]) state = init_state for i in range(119): state = evolve_state(state, rules) if '################' in state: rem = i + 1 #print(state[:180]) #print(rem) first_trivial_state = evolve_state(state, rules) # Generation 120 potlist = [] for index, symbol in enumerate(first_trivial_state, -LEFTPAD): if symbol == '#': potlist.append(index) print(sum_potlist_after_time(potlist, 50000000000, 120)) return
def do_part_1(day, test=False): lines = input_lines(day, test=test) positions = [] velocities = [] for line in lines: pos_vector, vel_vector = digest_line(line) positions.append(pos_vector) velocities.append(vel_vector) L1_0 = L1(positions) advance_time(positions, velocities) L1_1 = L1(positions) diff = L1_0 - L1_1 guess = int(L1_0 / diff) advance_time(positions, velocities, secs=guess) for i in range(20): print_portion(positions) print(L1(positions)) # Added for part 2 if L1(positions) == 6213: print(guess + 1 + i) advance_time(positions, velocities) return
for k in list(allergens.keys()): allergens[k] = allergens[k] - set([ingredient]) allergens[allergen] = set([ingredient]) rev = reverse_map(allergens) for i, (ingredients, in_allergens) in enumerate(recipes): booked = set() for ing in ingredients: booked |= rev[ing] for alg in in_allergens: if alg not in booked: return False return True input = utils.input_lines(test=False) input = [(a.split(' '), [bb.replace(')', '') for bb in b.split(', ')]) for a, b in [i.split(' (contains ') for i in input]] recipes, reverse = defaultdict(set), defaultdict(set) ingreds, allergs = set(), set() for ingredients, allergerns in input: for ingredient in ingredients: ingreds.add(ingredient) for allergen in allergerns: allergs.add(allergen) recipes[ingredient].add(allergen) reverse[allergen].add(ingredient) cant_allergens = set()
import utils from collections import defaultdict input = utils.input_lines(generator=int, test=False) jolts = sorted(input) deltas = defaultdict(int) deltas[jolts[0]] = 1 deltas[3] = 1 for (v1, v2) in utils.window(jolts): deltas[v2 - v1] += 1 print(deltas[1] * deltas[3]) g = utils.Graph() jolts = [0] + jolts + [jolts[-1] + 3] for i in range(len(jolts)): g.add_node(jolts[i]) for v0 in jolts[i + 1:]: if v0 - jolts[i] <= 3: g.add_edge(jolts[i], v0, v0 - jolts[i]) def node_cost(g, node, weights): if node in weights: return weights[node] if len(g.edges[node]) == 0:
def do_part_1(day, test=False): lines = input_lines(day, test=test) data = list(map(int, lines[0].split())) print(sum_metadata(data)) return
def do_part_2(day, test=False): lines = input_lines(day, test=test) data = list(map(int, lines[0].split())) print(sum_weightedvalue(data)) return
values, operators = [], [] for token in expression: if token == ' ': continue elif token == '(': operators.append(token) elif token == ')': top = operators[-1] while top and top != '(': values.append(operators.pop()(values.pop(), values.pop())) top = operators[-1] operators.pop() # Discard the '(' elif token in ['+', '*']: top = operators[-1] if operators else None while top and top == add: values.append(operators.pop()(values.pop(), values.pop())) top = operators[-1] if operators else None operators.append(add if token == '+' else mul) else: values.append(int(token)) while operators: values.append(operators.pop()(values.pop(), values.pop())) return values[0] rows = utils.input_lines() print(sum([a(row) for row in utils.input_lines()])) print(sum([shunting_yard(row) for row in utils.input_lines()]))
ship = utils.Coord2D(0, 0) for instruction, value in input: if instruction == 'N': waypoint.y += value elif instruction == 'S': waypoint.y -= value elif instruction == 'E': waypoint.x += value elif instruction == 'W': waypoint.x -= value elif instruction == 'L': for i in range(value // 90): rotate90L(ship, waypoint) elif instruction == 'R': for i in range(value // 90): rotate90R(ship, waypoint) elif instruction == 'F': dx, dy = waypoint.x - ship.x, waypoint.y - ship.y ship.x += dx * value ship.y += dy * value waypoint.x += dx * value waypoint.y += dy * value print(abs(ship.x) + abs(ship.y)) input = utils.input_lines(generator=lambda x: (x[0], int(x[1:])), test=False) a(input) b(input)
from utils import input_lines, window from re import sub seats = [int(sub('[BR]','1', sub(r'[FL]','0',p)), 2) for p in input_lines()] print(max(seats)) # A print([lo+1 for lo, mid in window(sorted(seats)) if lo+1 != mid][0]) # B
if mask[i] == '0': l.append(s[i]) return "".join(l) def b(program): data = dict() mask = '' for row in program: if row[0:4] == 'mask': mask = row[7:] else: loc, num = [ int(i) for i in re.match(r'mem\[(\d+)\] = (\d+)', row).groups() ] adresses = [] inp = interleave(mask, loc) adresses = explode(inp) for a in adresses: data[a] = num print(sum(data.values())) program = utils.input_lines(test=False) a(program) b(program)
prod = reduce(lambda a, b: a * b, n) for n_i, a_i in zip(n, a): p = prod // n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a // b a, b = b, a % b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 input = utils.input_lines() departure, buses = int(input[0]), [(t, int(x)) for t, x in enumerate(input[1].split(',')) if x != 'x'] mini = sorted([(bus * (1 + departure // bus) - departure, bus) for t, bus in buses])[0] print(mini[0] * mini[1]) times, primes = list(zip(*buses)) times = [-t for t in times] print(chinese_remainder(primes, times))