from collections import defaultdict from utils.io_util import read_file # input_path = 'inputs/day17_test.txt' input_path = 'inputs/day17.txt' inputs = read_file(input_path) class Grid: def __init__(self, inputs): self.grid = defaultdict(int) self.x_min = self.x_max = 0 self.y_min = self.y_max = 0 self.z_min = self.w_min = 0 self.z_max = self.w_max = 1 self.init_grid(inputs) def init_grid(self, inputs): """Inputs represent a 2d grid""" for i in range(len(inputs)): for j in range(len(inputs[i])): self.grid[(i, j, 0, 0)] = 0 if inputs[i][j] == '.' else 1 self.x_max = len(inputs) self.y_max = len(inputs[i]) def count_active(self, x, y, z, w): n_active = 0 for dx in (-1, 0, 1): for dy in (-1, 0, 1):
from utils.io_util import read_file # input_path = 'inputs/day9_test.txt' input_path = 'inputs/day9.txt' nums = [int(n) for n in read_file(input_path)] def process_nums(nums, preamble_len): # The rest head = 0 for n in nums[preamble_len:]: valid_sums = [] for i in range(head, head+preamble_len-1): for j in range(head+1, head+preamble_len): valid_sums.append(nums[i] + nums[j]) if n not in valid_sums: print(f'Invalid number found: {n}') return n head += 1 def find_cont_nums(nums, target): for i in range(len(nums)): for j in range(i+1, len(nums)): if sum(nums[i:j]) > target: break if sum(nums[i:j]) == target: print('Found the set:', nums[i:j])
else: print(f'Invalid cmd {cmd}') assert lo == hi, "lo must equals high after the binary search" return lo def get_seat(input): row = get_pos(input[:7], 0, 127) col = get_pos(input[7:], 0, 7) seat_id = row * 8 + col return row, col, seat_id assert get_seat('BFFFBBFRRR') == (70, 7, 567) assert get_seat('FFFBBBFRRR') == (14, 7, 119) assert get_seat('BBFFBBFRLL') == (102, 4, 820) inputs = io_util.read_file('inputs/day5.txt') ids = [] for input in inputs: _, _, seat_id = get_seat(input) ids.append(seat_id) ids.sort() for i in range(1, len(ids) - 1): if ids[i] - 1 != ids[i-1]: print(f'{ids[i] - 1} is your seart') if ids[i] + 1 != ids[i+1]: print(f'{ids[i] + 1} is your seart')
from collections import Counter, defaultdict from utils.io_util import read_file # input_path = 'inputs/day11_test1.txt' input_path = 'inputs/day11.txt' map = read_file(input_path) nrows = len(map) ncols = len(map[0]) def print_map(map): for row in map: print(row) def count_adjacent_seats(map, i, j): occupied = 0 for di, dj in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]: if 0 <= i+di < nrows and 0 <= j+dj < ncols and map[i+di][j+dj] == '#': occupied += 1 return occupied def count_adjacent_seats_2(map, i, j): occupied = 0 directions = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)] for di, dj in directions: ii, jj = i + di, j + dj while 0 <= ii < nrows and 0 <= jj < ncols: if map[ii][jj] == '.': ii, jj = ii + di, jj + dj
from utils.io_util import read_file, console_decode_line input_file = 'inputs/day8_test.txt' input_file = 'inputs/day8.txt' inputs = read_file(input_file) def console_run(lines): line_curr_idx = 0 line_indices = [] accumulator = 0 while line_curr_idx not in line_indices and line_curr_idx < len(lines): line_indices.append(line_curr_idx) line_inc, acc_inc = console_decode_line(lines[line_curr_idx]) line_curr_idx += line_inc accumulator += acc_inc return line_curr_idx, accumulator def fix_console(lines): for i, line in enumerate(lines): if 'nop' in line or 'jmp' in line: if 'nop' in line: line_new = line.replace('nop', 'jmp') elif 'jmp' in line: line_new = line.replace('jmp', 'nop') lines_new = lines[:i] + [line_new] + lines[i + 1:]
# %% Import data import math from collections import defaultdict from re import match from utils.io_util import read_file inputs = read_file('inputs/day21_test.txt') inputs = read_file('inputs/day21.txt') all_ingradients = [] allergens = defaultdict(set) # Process each line for input in inputs: curr_ingradients, curr_allergens = input.split(' (') curr_ingradients = set(curr_ingradients.split(' ')) curr_allergens = curr_allergens[9:-1] curr_allergens = set(curr_allergens.split(', ')) all_ingradients.extend(curr_ingradients) for allergen in curr_allergens: allergens[allergen] = allergens.get( allergen, curr_ingradients).intersection(curr_ingradients) def print_dict(d): for k, v in d.items(): print(k, v) # %% Let's identify all the allergens
def ocpx_report_forms(unit_file, set_value=1.5, save_file=None): result = list() unit_data = read_file(unit_file, types=unit_type, skip_head=True) last_day = "" last_time = "" last_imp = 0 last_clk = 0 last_consume = 0 last_cpc_5 = 0.0 last_cpm_5 = 0.0 last_cpc_acc = 0.0 last_cpm_acc = 0.0 last_update_flag = -1 for record in unit_data: sp_speed = record[17] update_flag = record[-1] if update_flag == last_update_flag: continue else: last_update_flag = update_flag tmp_record = list() cur_day = record[0] if cur_day != last_day: print(last_day, cur_day) last_cpc_5 = 0.0 last_cpm_5 = 0.0 last_cpc_acc = 0.0 last_cpm_acc = 0.0 last_imp = record[11] last_clk = record[12] last_consume = record[5] last_day = cur_day last_time = record[1] continue cur_time = record[1] imp_acc = record[11] clk_acc = record[12] consume_acc = record[5] imp_5 = imp_acc - last_imp clk_5 = clk_acc - last_clk consume_5 = consume_acc - last_consume last_imp = imp_acc last_clk = clk_acc last_consume = consume_acc if imp_5 < 0 or clk_5 < 0 or consume_5 < 0: continue tmp_record.extend([cur_day, cur_time, imp_acc, clk_acc, consume_acc, imp_5, clk_5, consume_5]) if imp_5 == 0: cpm_5 = last_cpm_5 else: cpm_5 = consume_5 / 1000.0 / imp_5 last_cpm_5 = cpm_5 if clk_5 == 0: cpc_5 = last_cpc_5 else: cpc_5 = consume_5 / 1000000.0 / clk_5 last_cpc_5 = cpc_5 if imp_acc == 0: cpm_acc = last_cpm_acc else: cpm_acc = consume_acc / 1000.0 / imp_acc last_cpm_acc = cpm_acc if clk_acc == 0: cpc_acc = last_cpc_acc else: cpc_acc = consume_acc / 1000000.0 / clk_acc last_cpc_acc = cpc_acc tmp_record.extend([cpc_5, cpm_5, cpc_acc, cpm_acc]) tmp_record.extend([record[13]/10.0, sp_speed, record[14]/10000.0, set_value]) result.append(tmp_record) last_day = cur_day if set_value: pd.DataFrame(result, columns=ocpx_rf_schema).to_csv(save_file, index=None)
from collections import Counter, defaultdict from utils.io_util import read_file input_path = 'inputs/day10_test1.txt' input_path = 'inputs/day10_test2.txt' input_path = 'inputs/day10.txt' nums = sorted([int(n) for n in read_file(input_path)] + [0]) def count_diff(nums): diffs = [nums[i] - nums[i - 1] for i in range(1, len(nums))] count = Counter(diffs) count[3] += 1 return count def dp(nums): dp_count = defaultdict(int) dp_count[0] = 1 for n in nums[1:]: dp_count[n] = dp_count[n - 1] + dp_count[n - 2] + dp_count[n - 3] return dp_count print(dp(nums))
inc = kp * pid_err_hist[0] - ki * pid_err_hist[1] + kd * pid_err_hist[2] pid_err_hist[2] = pid_err_hist[1] pid_err_hist[1] = pid_err_hist[0] return inc def get_new_price(consume, click): act_val = consume / 1000000.0 / (click + 0.0001) * 10000 pid_inc = pid_core(10000, act_val) if abs(pid_inc) >= 30000: pid_inc = pid_inc / abs(pid_inc) * 30000 curr_pid = last_pid + pid_inc print("curr cpc: {}, last pid: {}, curr pid inc: {}, curr pid: {} ...". format(act_val, last_pid, pid_inc, curr_pid)) return curr_pid if __name__ == "__main__": from utils.io_util import read_file # rt_hist = [(7834500, 1084, 6), (16241410, 1649, 8), (24330900, 2234, 16)] rt_hist = read_file("../data/pid_test", [int, int, int], False) counter = 0 for tmp_rt in rt_hist: counter += 1 if counter == 20: # break last_pid = 20 print("=======================================") last_pid = get_new_price(tmp_rt[2], tmp_rt[1]) # print(last_pid)
import re from utils.io_util import read_file # input_path = 'inputs/day14_test.txt' input_path = 'inputs/day14.txt' instructions = read_file(input_path) def apply_bitmask(addr_in, bitmask): """Both value and bitmask are 36-bit string""" addrs_out = [''] for x, m in zip(addr_in, bitmask): addrs_out_new = [] if m == '0': for i in range(len(addrs_out)): addrs_out_new.append(addrs_out[i] + x) elif m == '1': for i in range(len(addrs_out)): addrs_out_new.append(addrs_out[i] + '1') elif m == 'X': for i in range(len(addrs_out)): addrs_out_new.append(addrs_out[i] + '0') addrs_out_new.append(addrs_out[i] + '1') addrs_out = addrs_out_new return addrs_out def apply_instrs(instructions): bitmask = ''
# %% from collections import defaultdict from utils.io_util import read_file filename = 'inputs/day24_test.txt' filename = 'inputs/day24.txt' inputs = read_file(filename) # inputs = ['nwwswee'] directions = { 'e': (1, 0), 'se': (0, 1), 'sw': (-1, 1), 'w': (-1, 0), 'nw': (0, -1), 'ne': (1, -1) } def parse_inputs(inputs): instrs = [] for line in inputs: instr = [] i = 0 while i < len(line): if line[i:i + 2] in ['se', 'sw', 'nw', 'ne']: instr.append(line[i:i + 2]) i += 2 elif line[i] in ['e', 'w']: instr.append(line[i]) i += 1 else:
from collections import deque from utils.io_util import read_file equations = read_file('inputs/day18.txt') def solve(eq): if '(' not in eq: return solve_simple(eq) while '(' in eq: n_left, n_right = 1, 0 left = eq.find('(') for i in range(left + 1, len(eq)): if eq[i] == '(': n_left += 1 elif eq[i] == ')': n_right += 1 if n_left == n_right: eq_reduced = eq[left + 1:i] res = solve(eq_reduced) eq = eq[:left] + str(res) + eq[i + 1:] break return solve_simple(eq) def solve_simple(equation): """Solve equation with no parenthesis""" assert '(' not in equation and ')' not in equation eq = equation.split(' ')
def reform(unit1, u1_save_f): u1_data = read_file(unit1, unit_types) u1_df = __every_minute_analysis(u1_data) u1_df.to_csv(u1_save_f, index=None)