def day2(submit_answer=False): data = get_data(day=2, year=2018).split("\n") checksum = box_checksum(data) common_id = find_common_box_id(data) if submit_answer: submit1(checksum, day=2, year=2018) submit2(common_id, day=2, year=2018) return checksum, common_id
def main(): input = get_data(day=9, year=2018) re_matcher = REMatcher(input) re_matcher.match(r"(\d+) players; last marble is worth (\d+) points") num_players = int(re_matcher.group(1)) num_marbles = int(re_matcher.group(2)) + 1 ans = problem1(num_players, num_marbles) submit1(ans) ans = problem2(num_players, num_marbles * 100) submit2(ans)
def main(): input = get_data(day=10, year=2018).split("\n") points = [] velocities = [] for i in input: reg = REMatcher(i) reg.match(r"position=\<\s*(-?\d+),\s*(-?\d+)\> velocity=\<(\s*-?\d+),\s*(-?\d+)\>") points.append((int(reg.group(1)), int(reg.group(2)))) velocities.append((int(reg.group(3)), int(reg.group(4)))) assert len(points) == len(input) == len(velocities) ans = problem1(points, velocities) #submit1(ans) submit2(ans)
def main(): input = get_data(day=12, year=2018).split("\n") init_state = input[0].split(': ')[1] rules_arr = input[2:] rules_arr = list( map(lambda x: (x.split(' => ')[0], x.split(' => ')[1]), rules_arr)) rules = {} for r, o in rules_arr: rules[r] = o ans = problem1(init_state, rules) submit1(ans) iteration, plant_sum, inc = problem2(init_state, rules) ans = int(((50000000000 - iteration) * inc) + plant_sum) print(iteration, inc, plant_sum, ans) submit2(ans)
def day5(submit_answer=False): data = get_data(day=5, year=2018) reduced_length = len(reduce(list(data))) all_units = set(data.lower()) new_reduced_lengths = {} for char in all_units: new_data = [c for c in data if c.lower() != char] new_reduced_lengths[char] = len(reduce(new_data)) fully_reduced = min(new_reduced_lengths.items(), key=lambda x: x[1])[1] if submit_answer: submit1(reduced_length, day=5, year=2018) submit2(fully_reduced, day=5, year=2018) return reduced_length, fully_reduced
def day4(submit_answer=False): data = sorted(get_data(day=4, year=2018).split("\n")) answer1 = 0 answer2 = None regex = re.compile(r"(\d+)") guards = collections.defaultdict(int) guard_total_sleep = collections.defaultdict(int) current_guard = 0 last_minute = 0 for action in data: if "begins shift" in action: year, month, day, hr, minute, current_guard = map( int, regex.findall(action)) last_minute = 0 else: year, month, day, hr, minute = map(int, regex.findall(action)) if "wakes" in action: for i in range(last_minute, minute): guards[(current_guard, i)] += 1 guard_total_sleep[current_guard] += 1 last_minute = minute id_of_max_slept = max(guard_total_sleep.items(), key=lambda x: x[1])[0] minute_of_max_overlap = max( [(min, overlap) for (id, min), overlap in guards.items() if id == id_of_max_slept], key=lambda x: x[1])[0] answer1 = id_of_max_slept * minute_of_max_overlap (id_of_max_overlaps, minute_of_max_overlap), overlaps = max(guards.items(), key=lambda x: x[1]) answer2 = id_of_max_overlaps * minute_of_max_overlap if submit_answer: submit1(answer1, day=4, year=2018) submit2(answer2, day=4, year=2018) return answer1, answer2
def day3(submit_answer=False): data = get_data(day=3, year=2018).split("\n") overlap_area = 0 none_overlap = None fabric = collections.defaultdict(int) regex = re.compile(r"(\d+)") for claim in data: groups = regex.findall(claim) id, left_edge, top_edge, width, height = map(int, groups) for x in range(0, width): for y in range(0, height): fabric[(x + left_edge, y + top_edge)] += 1 for num_claims in fabric.values(): if num_claims > 1: overlap_area += 1 for claim in data: groups = regex.findall(claim) id, left_edge, top_edge, width, height = map(int, groups) failed = False for x in range(0, width): for y in range(0, height): if fabric[(x + left_edge, y + top_edge)] != 1: failed = True break if failed: break if not failed: none_overlap = id if submit_answer: submit1(overlap_area, day=3, year=2018) submit2(none_overlap, day=3, year=2018) return overlap_area, none_overlap
print(f'{" Sample ":*^40}') result = do_it(9, 25, debug=True) print(result.winner) things = ( (10, 1618, 8317), (13, 7999, 146373), (17, 1104, 2764), (21, 6111, 54718), (30, 5807, 37305), ) for player, last_marble, expected_score in things: result = do_it(player, last_marble) assert result.winner.score == expected_score, f'Score was {result.winner.score} not {expected_score}' print('Checked', player, last_marble, expected_score) print(f'{" End Sample ":*^40}') print('\n') print(f'{" Live ":*^40}') data = get_data(day=DAY).split() player_count = int(data[0]) last_marble = int(data[-2]) result = do_it(player_count, last_marble, progress=True) #score = result.most_common(1)[0][1] # result = do_it(player_count, last_marble*100, progress=True) #submit1(score) submit2(result.winner.score) print(f'{" Done ":*^40}')
:return: the list of data from the first half that pairs with the second half >>> 2 * sum(find_cyclically_paired_elements("1212")) 6 >>> 2 * sum(find_cyclically_paired_elements("1221")) 0 >>> 2 * sum(find_cyclically_paired_elements("123425")) 4 >>> 2 * sum(find_cyclically_paired_elements("123123")) 12 >>> 2 * sum(find_cyclically_paired_elements("12131415")) 4 """ return [ int(lst[i]) for i in range(len(lst) // 2) if lst[i] == lst[len(lst) // 2 + i] ] if __name__ == '__main__': session = aocd.get_cookie() data = aocd.get_data(day=1, year=2017, session=session) a1 = sum(find_paired_elements(data)) print("a1 = %r" % a1) aocd.submit1(a1, day=1, year=2017, session=session, reopen=False) a2 = 2 * sum(find_cyclically_paired_elements(data)) print("a2 = %r" % a2) aocd.submit2(a1, day=1, year=2017, session=session, reopen=False)
def day6(submit_answer=False): data = get_data(day=6, year=2018).split("\n") answer1 = 0 answer2 = 0 locations = {} total_safe_area = 0 regex = re.compile(r"(\d+)") coords = [] for coord in data: x, y = map(int, regex.findall(coord)) coords.append((x, y)) max_x = max(coords, key=lambda x: x[0])[0] max_y = max(coords, key=lambda x: x[1])[1] min_x = min(coords, key=lambda x: x[0])[0] min_y = min(coords, key=lambda x: x[1])[1] points_on_edge = set() for y in range(min_x, max_y + 1): for x in range(min_x, max_x + 1): closest_point = coords[0] closest_distance = 10000000000 equidistance = -1 sum_distances = 0 for coord in coords: pos_x, pos_y = coord distance = abs(pos_x - x) + abs(pos_y - y) sum_distances += distance if distance < closest_distance: closest_point = coord closest_distance = distance elif distance == closest_distance: equidistance = distance if closest_distance == equidistance: closest_point = None """if closest_point is None: print(".", end="") else: if closest_distance > 0: print(string.ascii_lowercase[coords.index(closest_point)], end="") else: print(string.ascii_uppercase[coords.index(closest_point)], end="") """ if closest_distance < 10000: locations[(x, y)] = closest_point if sum_distances < 10000: total_safe_area += 1 if x == min_x or x == max_x or y == min_y or y == max_y: points_on_edge.add(closest_point) areas_to_count = [coord for coord in coords if coord not in points_on_edge] areas = collections.defaultdict(int) for _, location in locations.items(): areas[location] += 1 areas = { location: area for location, area in areas.items() if location in areas_to_count } max_area = max(areas.items(), key=lambda x: x[1])[1] if submit_answer: submit1(max_area, day=6, year=2018) submit2(total_safe_area, day=6, year=2018) return max_area, total_safe_area
try: total += self.children[i - 1].weird_sum except IndexError: total += 0 #it's skipped return total def part_one(lines): print('==== Part one ====') result = Node([int(x) for x in lines[0].split()]) print('==== End part one ====') return result print(f'{" Sample ":*^40}') result = part_one(sample_1_lines) print(result) result.blerp() print(result.meta_sum) print(result.weird_sum) print(f'{" End Sample ":*^40}') print('\n') print(f'{" Live ":*^40}') data = get_data(day=DAY) result = part_one(data.split('\n')) submit1(result.meta_sum) submit2(result.weird_sum) print(f'{" Done ":*^40}')
curr_workers = 0 seconds = 0 while len(q) > 0 or curr_workers > 0: g, q, processing_nodes, processed_steps, curr_workers, order = work( g, q, processing_nodes, processed_steps, curr_workers, order) # work on each node in process #print(seconds, processing_nodes, q, processed_steps) q.sort() i = 0 curr_length = len(q) while i < curr_length and curr_workers < tot_workers: # look at work queue and determine if anything can be done curr_step = q[i] prereqs = g[curr_step]['parents'] if len(prereqs.intersection(processed_steps)) == len( prereqs): # we've acquired all prereqs for this step processing_nodes[curr_step] = 0 q.pop(i) # remove from q curr_length -= 1 if curr_workers < tot_workers: curr_workers += 1 if curr_workers == tot_workers: break else: # don't have all prereqs i += 1 # try the next one seconds += 1 return seconds - 1 submit1(problem1(g, sources, sinks)) submit2(problem2(g, sources, sinks))
if c not in visited: q.append(c) return tot def sum_metadata(node, metadata): return sum(metadata) def calc_metadata_indices(node, metadata_indices): metadata = 0 num_children = len(node.children) for mindex in metadata_indices: if num_children > 0: mindex -= 1 if mindex < len(node.children): metadata += node.children[mindex].metadata else: metadata += mindex return metadata data = get_data(day=8, year=2018).split(" ") data = list(map(lambda x: int(x), data)) nodes, _ = parse_data(data, 1, sum_metadata) ans = problem1(nodes[0], lambda x: x) nodes, _ = parse_data(data, 1, calc_metadata_indices) submit2(nodes[0].metadata)
def day7(submit_answer=False): data = get_data(day=7, year=2018).split("\n") regex = re.compile(r"tep (.)") dependencies = collections.defaultdict(list) reverse_dependencies = collections.defaultdict(list) all_dependencies = set() for dep in data: dependency, dependent = regex.findall(dep) all_dependencies.add(dependent) dependencies[dependent].append(dependency) reverse_dependencies[dependency].append(dependent) zero_dependencies = [step for step in reverse_dependencies.keys() if step not in all_dependencies] order = [] available = list(zero_dependencies) while len(available) > 0: available.sort() current = available.pop(0) order.append(current) for dependent in reverse_dependencies[current]: # If all dependencies are fulfilled if all(dependency in order for dependency in dependencies[dependent]): available.append(dependent) completion_order = "".join(order) available = zero_dependencies order = [] workers = [(".", 0)] * 5 time_elapsed = 0 while True: for i, (current, time) in enumerate(workers): if time <= 0: if current != ".": order.append(current) for dependent in reverse_dependencies[current]: # If all dependencies are fulfilled if all(dependency in order for dependency in dependencies[dependent]): available.append(dependent) for i, (job, time) in enumerate(workers): if time <= 0: # Give them a new job available.sort() if len(available) > 0: job = available.pop(0) time = string.ascii_uppercase.index(job) + 61 else: job = "." time = 0 workers[i] = (job, time - 1) have_jobs = any(job != "." for job, time in workers) if not have_jobs and len(available) == 0: break else: time_elapsed += 1 if submit_answer: submit1(completion_order, day=7, year=2018) submit2(time_elapsed, day=7, year=2018) return completion_order, time_elapsed
workers[s] -= 1 if workers[s] <= 0: #print('Worker', s, 'done') del workers[s] steps_left.remove(s) result += s for blocked_step in blocked_by[s]: blocking[blocked_step].remove(s) if not blocking[blocked_step]: del blocking[blocked_step] time += 1 return time, result print('==== End part one ====') print(f'{" Sample ":*^40}') result = part_one(sample_1_lines) print(result) for c in result[1]: print(step_time(c)) print(f'{" End Sample ":*^40}') print('\n') print(f'{" Live ":*^40}') data = get_data(day=DAY) result = part_one(data.split('\n'), max_workers=5) print(result) submit2(result[0]) print(f'{" Done ":*^40}')