def speak(x, turn): if len(number_history[x]) > 1: x = number_history[x][-1] - number_history[x][-2] else: x = 0 spoken_numbers.append(x) number_history[x].append(turn) IO.write(turn, x)
def parse_file(): passport = {} for line in IO.read_all(): passport.update(get_entries(line)) if len(line) < 3 or line[-1] != '\n': pass_list.append(passport) passport = {}
def build_graph(): ans = Graph() for line in IO.read_all(): match = re.match(r"(.+) contain (.+)", line) parent_group = match.group(1) child_group = match.group(2) if "no other bag" in child_group: continue bag_matches = re.findall(r"((\d+) ([\w\s]+))[,.]", child_group) for bag in bag_matches: weight = int(bag[1]) ans.add(format_bag_string(parent_group), format_bag_string(bag[2]), weight) return ans
ans += self.weights[(node, to)] * self.get_weight(to) return ans def format_bag_string(bag): return bag.replace("bags", "").replace("bag", "").strip() sys.setrecursionlimit(4000) def build_graph(): ans = Graph() for line in IO.read_all(): match = re.match(r"(.+) contain (.+)", line) parent_group = match.group(1) child_group = match.group(2) if "no other bag" in child_group: continue bag_matches = re.findall(r"((\d+) ([\w\s]+))[,.]", child_group) for bag in bag_matches: weight = int(bag[1]) ans.add(format_bag_string(parent_group), format_bag_string(bag[2]), weight) return ans graph = build_graph() IO.write(len(graph.get_callees("shiny gold"))-1) IO.write(graph.get_weight("shiny gold")-1)
from src.helper import IO def code_to_xy(code): code = code.replace('B', '1').replace('F', '0').replace('L', '0').replace('R', '1') return int(code[:7], 2), int(code[7:], 2) def xy_to_id(xy): return xy[0] * 8 + xy[1] input_data = IO.read_all() # IO.write(max([xy_to_id(code_to_xy(line.strip())) for line in input_data if len(line) > 2])) ids = [ xy_to_id(code_to_xy(line.strip())) for line in input_data if len(line) > 2 ] ids_set = set(ids) for seat_id in ids: if seat_id - 2 in ids_set and seat_id - 1 not in ids_set: IO.write(seat_id - 1)
def parse_instruction(to_parse): instr, instr_args = to_parse[0], [int(to_parse[1:])] if instr in Ferry.dir_map: instr_args = [Ferry.dir_map[instr]] + instr_args if instr == "L": instr_args[-1] = -instr_args[-1] return instr, instr_args ferry = WaypointFerry() ferry_instr = { "N": ferry.move_dir, "E": ferry.move_dir, "S": ferry.move_dir, "W": ferry.move_dir, "L": ferry.turn, "R": ferry.turn, "F": ferry.move_forward } lines = IO.read_all() for line in lines: if len(line) < 2: continue instruction, args = parse_instruction(line) ferry_instr[instruction](*args) IO.write(int(abs(ferry.pos.real) + abs(ferry.pos.imag)))
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 # --- NOT MY CODE ENDS HERE file_input = IO.read_all() orig_timestamp, IDs = int(file_input[0]), [ int(x) if x[0] != 'x' else 0 for x in file_input[1].split(",") ] IO.write(orig_timestamp, IDs) bus = min([(((orig_timestamp - 1) // ID * ID + ID), ID) for ID in IDs if ID > 0]) IO.write(bus, (bus[0] - orig_timestamp) * bus[1]) IO.write( chinese_remainder(*zip(*[(ID[1], ID[1] - ID[0]) for ID in enumerate(IDs) if ID[1] > 0])))
from src.helper import IO import re import itertools def powerset(iterable): return itertools.chain.from_iterable( itertools.combinations(iterable, index) for index in range(len(iterable) + 1)) mask_one, mask_zero, float_values = None, None, None memory = dict() for line in IO.read_all(): match_mask = re.match(r"mask = ([10X]{36})", line) match_memo = re.match(r"mem\[(\d+)] = (\d+)", line) if match_mask: mask = [(index, int(bit) if bit != "X" else bit) for index, bit in enumerate(match_mask.group(1))] mask_one = sum([(1 << (35 - index)) for index, bit in mask if bit == 1 or bit == "X"]) # mask_zero = ((1 << 36) - 1) ^ sum([(1 << (35-index)) for index, bit in mask if bit == 0]) float_values = [(1 << (35 - index)) for index, bit in mask if bit == "X"] if match_memo: # memory[int(match_memo.group(1))] = mask_one | int(match_memo.group(2)) & mask_zero for subset in powerset(float_values): mask_zero = (2 << 36) - 1 - sum(subset) memory[(mask_one | int(match_memo.group(1))) & mask_zero] = int( match_memo.group(2))
for line in IO.read_all(): passport.update(get_entries(line)) if len(line) < 3 or line[-1] != '\n': pass_list.append(passport) passport = {} def is_valid(passport): # for field in mandatory_fields: # if field not in passport: # return False # return True for field in mandatory_fields: if field not in passport: return False if not checkers[field](passport[field]): return False for field in optional_fields: if field not in passport: continue if not checkers[field](passport[field]): return False return True parse_file() IO.write(len([passport for passport in pass_list if is_valid(passport)]))
from src.helper import IO def init_group_set(): # return set() return set([chr(ascii_code) for ascii_code in range(ord('a'), ord('z')+1)]) groups = [] group = init_group_set() for line in IO.read_all(): line_ch = [ch for ch in line if 'a' <= ch <= 'z'] # group.update(line_ch) if len(line) > 0 and 'a' <= line[0] <= 'z': group = set([ch for ch in group if ch in line_ch]) if len(line) < 2 or line[-1] != '\n': if len(group) > 0: groups.append(group) group = init_group_set() IO.write(sum([len(x) for x in groups]))
from src.helper import IO import collections COUNT_TURNS = 2020 starting_numbers = [int(x) for x in IO.read_all()[0].split(",")] spoken_numbers = [] number_history = collections.defaultdict(lambda: list()) def speak(x, turn): if len(number_history[x]) > 1: x = number_history[x][-1] - number_history[x][-2] else: x = 0 spoken_numbers.append(x) number_history[x].append(turn) IO.write(turn, x) for i in range(1, COUNT_TURNS + 1): if i - 1 < len(starting_numbers): spoken_numbers.append(starting_numbers[i - 1]) number_history[starting_numbers[i - 1]].append(i) else: speak(spoken_numbers[-1], i) IO.write(spoken_numbers[-1])
from src.helper import IO import re valid_pass_count = 0 for line in IO.read_all(): match = re.match(r"(\d*-\d*)\s*(\w):\s*(\w+)", line) if match is None: continue bounds = [int(x) for x in match.group(1).split('-')] character = match.group(2) word = match.group(3) count = word.count(character) # if bounds[0] <= count <= bounds[1]: # valid_pass_count += 1 if [word[bounds[0] - 1], word[bounds[1] - 1]].count(character) == 1: valid_pass_count += 1 IO.write(valid_pass_count)
from src.helper import IO input_nums = [int(x) for x in IO.read_all() if len(x) > 0] input_nums.append(0) input_nums.append(max(input_nums) + 3) input_nums = sorted(input_nums) pair_diff = [y - x for x, y in zip(input_nums, input_nums[1:])] IO.write(pair_diff.count(1) * pair_diff.count(3)) possibilities = {0: 1} for value in input_nums[1:]: possibilities[value] = possibilities.get(value - 1, 0) + possibilities.get( value - 2, 0) + possibilities.get(value - 3, 0) IO.write(possibilities[max(input_nums)])
from src.helper import IO import functools tree_map = [line.strip() for line in IO.read_all()] # vel, grid_pos = complex(3, 1), complex(0, 0) # tree_counter = 0 grid_height, grid_width = len(tree_map), len(tree_map[0]) def is_tree(x, y): return tree_map[y][x % grid_width] == '#' def get_coord(complex_num): return int(complex_num.real), int(complex_num.imag) def walk(velocity): grid_pos = complex(0, 0) tree_counter = 0 while grid_pos.imag < grid_height: if is_tree(*get_coord(grid_pos)): tree_counter += 1 grid_pos += velocity return tree_counter # while grid_pos.imag < grid_height: # if is_tree(*get_coord(grid_pos)): # tree_counter += 1
execution_set.add(pointer) keyword, args = instr[pointer].split() if keyword == "nop": pointer += 1 elif keyword == "jmp": pointer += int(args) elif keyword == "acc": accumulator += int(args) pointer += 1 return accumulator, b_finished # IO.write(run_instructions(IO.read_all())) orig_instr = IO.read_all() for index in range(len(orig_instr)): instr_type = orig_instr[index].split()[0] saved_line = orig_instr[index] if instr_type == "nop": orig_instr[index] = orig_instr[index].replace("nop", "jmp") if instr_type == "jmp": orig_instr[index] = orig_instr[index].replace("jmp", "nop") acc, flag = run_instructions(orig_instr) if flag is True: IO.write(acc) break orig_instr[index] = saved_line
from src.helper import IO import itertools import copy seats = [[x for x in line.strip()] for line in IO.read_all()] n, m = len(seats), len(seats[0]) def seat_trace(pos_x, pos_y, vel_x, vel_y): if vel_x == 0 and vel_y == 0: return seats[pos_x][pos_y] pos_x += vel_x pos_y += vel_y while pos_x in range(n) and pos_y in range(m): if seats[pos_x][pos_y] != '.': return seats[pos_x][pos_y] pos_x += vel_x pos_y += vel_y return '.' n_iter = 0 while True: next_seats = copy.deepcopy(seats) for line, coll in itertools.product(range(n), range(m)): # adj_seats = [seats[i][j] for i in range(max(0, line-1), min(n, line+2)) # for j in range(max(0, coll-1), min(m, coll+2))] adj_seats = [seat_trace(line, coll, i, j) for i in range(-1, 2) for j in range(-1, 2)] occup_cnt = adj_seats.count('#')
def is_sum_of_pair(candidate, nums): return candidate in [ nums[i] + nums[j] for i in range(len(nums)) for j in range(len(nums)) if i != j ] def find_impostor(num_arr, preamble): for index in range(preamble, len(num_arr)): if not is_sum_of_pair(num_arr[index], num_arr[index - preamble:index]): return num_arr[index] return -1 # IO.write(find_impostor([int(x) for x in IO.read_all() if len(x) > 0], 25)) input_nums = [int(x) for x in IO.read_all() if len(x) > 0] impostor = find_impostor(input_nums, 25) partial_sums = [0] for x in input_nums: partial_sums.append(partial_sums[-1] + x) partial_set = set(partial_sums) left = right = 0 for p_sum in partial_sums: partial_set.remove(p_sum) to_search = impostor + p_sum if to_search in partial_set: left = p_sum right = to_search break
from src.helper import IO arr = [int(line) for line in IO.read_all()] # sum_product = {x+y: x*y for x in arr for y in arr} sum_product = {x+y+z: x*y*z for x in arr for y in arr for z in arr} IO.write(sum_product[2020])