import aoc_helper directions_data = aoc_helper.get_input("2", "string") # Part 1 x = 0 y = 0 for line in directions_data: v_x = 0 v_y = 0 (direction, steps) = line.split(" ") assert direction in ["forward", "down", "up"] if direction == "forward": v_x = int(steps) if direction == "down": v_y = int(steps) if direction == "up": v_y = int(steps) * -1 x = x + v_x y = y + v_y # print(direction, steps, x, y) # print(x,y) print("Part 1", x * y) # Part 2 x = y = aim = 0 for line in directions_data: v_x = v_y = v_aim = 0 (direction, steps) = line.split(" ")
import math import aoc_helper import re from collections import defaultdict data = aoc_helper.get_input("input22", "plain").strip() # data = aoc_helper.get_input("input21_sample", "string") # print(data) left, right = data.split("\n\n") player_A = [int(x) for x in left.split("\n")[1:]] player_B = [int(x) for x in right.split("\n")[1:]] # print(player_A) # print(player_B) # Game ends if one of the decks is empty def is_game_over(player_A, player_B): if not player_A or not player_B: return True return False def calculate_score(player_A, player_B): score_A = 0 score_B = 0 for i, card in enumerate(reversed(player_A), 1): score_A += i * card for i, card in enumerate(reversed(player_B), 1): score_B += i * card
import aoc_helper from functools import reduce data = aoc_helper.get_input('input10') #print(data) jolts = data device_builtin_joltage = max(jolts) + 3 charging_outlet_joltage = 0 jolts.append(charging_outlet_joltage) jolts.append(device_builtin_joltage) jolts.sort() print(jolts) one_jolt_difference = 0 three_jolt_difference = 0 for i in range(len(jolts) - 1): diff = jolts[i + 1] - jolts[i] if diff == 1: one_jolt_difference += 1 elif diff == 3: three_jolt_difference += 1 else: print(diff) print(one_jolt_difference * three_jolt_difference)
In total, this set of adapters can connect the charging outlet to your device in 19208 distinct arrangements. You glance back down at your bag and try to remember why you brought so many adapters; there must be more than a trillion valid ways to arrange them! Surely, there must be an efficient way to count the arrangements. What is the total number of distinct ways you can arrange the adapters to connect the charging outlet to your device? """ from typing import List from aoc_helper import get_input from numpy import diff data = list(map(int, get_input())) def get_diffs(data: List[int]) -> int: """get_diffs its a helper function to compute the product of the derivative of the input data. Args: data (List[int]): input data converted to list of ints. Returns: int: the product of the count of values where the derivative equals 1 and 3. """ temp = list(diff(sorted(data.copy() + [0, max(data) + 3]))) return temp.count(1) * temp.count(3)
bbbbbbbaaaabbbbaaabbabaaa bbbababbbbaaaaaaaabbababaaababaabab ababaaaaaabaaab ababaaaaabbbaba baabbaaaabbaaaababbaababb abbbbabbbbaaaababbbbbbaaaababb aaaaabbaabaaaaababaa aaaabbaabbaaaaaaabbbabbbaaabbaabaaa aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba After updating rules 8 and 11, how many messages completely match rule 0? """ from aoc_helper import get_input import re data = get_input() rules = data[:131] def build_re(rules, code=0): for line in rules: if int(line[:line.find(':')]) == code: rule = line.split(': ')[1] if '"' in rule: return f'{rule[1]}' elif '|' in rule: rule = rule.replace('|', '').split() rule = list(map(int, rule)) if len(rule) == 2: return f'({build_re(rules, rule[0])}|{build_re(rules, rule[1])})' else:
# -*- coding: utf-8 -*- """ Created on Fri Dec 4 05:53:32 2020 @author: gape """ import aoc_helper import re data = aoc_helper.get_input(4, force=True) print('Day 4 input:') print(data) print('Total input length: ', len(data)) print('Total input row length: ', len(data.split('\n'))-1) print("\n############################################################\n") fields = ['byr', 'iyr','eyr', 'hgt', 'hcl', 'ecl', 'pid', 'cid'] passports = [] for row in data.split('\n\n'): passport = dict() for p in row.split(): k, v = p.split(':') passport[k] = v passports.append(passport) count = 0 for p in passports:
import aoc_helper from functools import reduce from itertools import product from collections import defaultdict import re data = aoc_helper.get_input('input19', 'plain').strip() # print(data) rules_data = data.split('\n\n')[0].split('\n') messages = data.split('\n\n')[1].split('\n') # print(rules_data) # print(messages) def parse_rules(rules_data): rules = {} for line in rules_data: line_split = line.split(': ') rule_id = line_split[0] line_split_values = line_split[1].split(' | ') sub_rules = [] for v in line_split_values: if v not in ['\"a\"', '\"b\"']: values = v.split(' ') else: values = v.replace('"', '') sub_rules.append(values) rules[rule_id] = sub_rules return rules
import math import aoc_helper import re from collections import defaultdict data = aoc_helper.get_input("input21", "string") # data = aoc_helper.get_input("input21_sample", "string") # print(data) foods = {} counts = defaultdict(int) all_allergens = set() all_ingredients = set() for line in data: (food, allergen_list) = line.split(" (contains ") allergen_list = allergen_list.replace(")", "").split(", ") ingredient_list = food.split(" ") # print(food) # print(allergen_list) foods[food] = allergen_list for ingredient in ingredient_list: all_ingredients.add(ingredient) for allergen in allergen_list: all_allergens.add(allergen) print(all_allergens) print(all_ingredients) ingredient_allergen_candidates = {i: set(all_allergens) for i in all_ingredients}
password_str = password.split(':')[1].strip() if min_ <= password_str.count(letter) <= max_: counter += 1 return counter def correct_passwords_2(passwords): """Get correct password based on the alternative policy (a letter a should appear exclusively in one of the positions b and c.) Args: passwords (List[str]): List of input data Returns: int: the number of correct passwords """ counter = 0 for password in passwords: i1, i2 = [int(i) for i in password.split(':')[0].split()[0].split('-')] letter = password.split(':')[0].split()[1] password_str = password.split(':')[1].strip() if (password_str[i1 - 1] == letter) ^ (password_str[i2 - 1] == letter): counter += 1 return counter passwords = get_input() print(f'Result: {correct_passwords_1(passwords)}') print(f'Result: {correct_passwords_2(passwords)}')
# -*- coding: utf-8 -*- """ Created on Fri Dec 3 05:58:29 2021 @author: gape """ from collections import Counter import aoc_helper data = aoc_helper.get_input(3, year=2021, force=True) print('Day 3 input:') print(data[:100]) print('Total input length: ', len(data)) print('Total input row length: ', len(data.split())) print() data = data.split('\n') nums = Counter() for d in data: for i, b in enumerate(d): if b == '1': nums[i] += 1 gamma = [] epsi = [] for i in range(12): if nums[i] > 500:
import aoc_helper from functools import reduce data = aoc_helper.get_input('input16', 'plain') data_parts = str(data).strip().split('\n\n') # print(data_parts) fields_data = data_parts[0].split('\n') my_ticket = data_parts[1].split('\n')[-1].split(',') other_tickets = data_parts[2].split('\n')[1:] # print(other_tickets) def parse_fields(fields_data): fields = {} for line in fields_data: (field_name, field_value_data) = line.split(': ') field_values = field_value_data.split(' or ') v = [] for value in field_values: low, high = value.split('-') v.append((int(low), int(high))) fields[field_name] = v return fields parsed_fields_data = parse_fields(fields_data) def parse_other_tickets(other_tickets_data): tickets = [] for line in other_tickets_data:
spoken. For example, given the same starting numbers as above: Given 0,3,6, the 30000000th number spoken is 175594. Given 1,3,2, the 30000000th number spoken is 2578. Given 2,1,3, the 30000000th number spoken is 3544142. Given 1,2,3, the 30000000th number spoken is 261214. Given 2,3,1, the 30000000th number spoken is 6895259. Given 3,2,1, the 30000000th number spoken is 18. Given 3,1,2, the 30000000th number spoken is 362. Given your starting numbers, what will be the 30000000th number spoken? """ from typing import List from aoc_helper import get_input data = list(map(int, get_input()[0].split(','))) def compute_last(start_set: List[int], number: int) -> int: """compute_last computes the nth number of the elves game given an input set. Args: start_set (List[int]): the input starting set parsed to ints. number (int): target number. Returns: int: the nth number of the game. """ memory = {} for turn in range(len(start_set)):
import aoc_helper from functools import reduce data = aoc_helper.get_input('input9') # print(data) # Definitions PREAMBLE_SIZE = 25 def is_valid_number(number, preamble): numbers = set(preamble) for num in preamble: if number - num in numbers: return True return False part1_idx = 0 for i in range(len(data) - PREAMBLE_SIZE): check_number = data[i + PREAMBLE_SIZE] preamble = data[:i + PREAMBLE_SIZE] if not is_valid_number(check_number, preamble): part1_idx = i + PREAMBLE_SIZE print("Part1:", data[part1_idx]) break # Part 2: result = data[part1_idx] found = False
import aoc_helper data = aoc_helper.get_input('input8', 'string') # print(data) def extract_instruction(instruction): operator = instruction.split(' ')[0] argument = int(instruction.split(' ')[1]) return operator, argument def execute_instructions(instructions): valid_operators = ['nop', 'acc', 'jmp'] seen_lines = set() curr_pos = 0 accumulator_value = 0 while True: next_instruction = instructions[curr_pos] operator, argument = extract_instruction(next_instruction) if curr_pos in seen_lines: #print('Part1', accumulator_value) break else: seen_lines.add(curr_pos) assert operator in valid_operators
import aoc_helper from collections import defaultdict data = aoc_helper.get_input("5", "string") paths = defaultdict(int) for line in data: points = line.split(" -> ") x1, y1 = points[0].split(",") x1 = int(x1) y1 = int(y1) x2, y2 = points[1].split(",") x2 = int(x2) y2 = int(y2) # only vertical and horizontal lines if x1 != x2 and y1 != y2: continue v_x = x2 - x1 if v_x > 0: v_x = 1 if v_x < 0: v_x = -1 v_y = y2 - y1 if v_y > 0: v_y = 1 if v_y < 0: v_y = -1 paths[(x1, y1)] += 1 while not (x1 == x2 and y1 == y2):
""" from itertools import combinations from numpy import prod from aoc_helper import get_input def search(nums, n): """search iterates over the list of combinations of groups of n ints to find a group that sums 2020. Args: nums (List[int]): input numbers n (int): number of elements in each combination. Returns: int: the product of the group of numbers that sum 2020. """ nums = list(combinations(nums, n)) for num_tup in nums: if sum(num_tup) == 2020: return prod(num_tup) # Transform to int the list of numbers data = [int(n) for n in get_input()] print(f'Result part 1: {search(data, 2)}') print(f'Result part 2: {search(data, 3)}')
# -*- coding: utf-8 -*- """ Created on Sun Dec 5 07:38:30 2021 @author: gape """ from collections import Counter import aoc_helper data = aoc_helper.get_input(5, year=2021, force=True).strip() print('Day 5 input:') print(data[:200]) print('Total input length: ', len(data)) print('Total input row length: ', len(data.split())) print() data = data.split('\n') horizontal = [] vertical = [] diagonal = [] for row in data: entry, exit = row.split(' -> ') entry = list(int(i) for i in entry.split(',')) exit = list(int(i) for i in exit.split(',')) if entry[1] == exit[1]: horizontal.append((entry, exit)) elif entry[0] == exit[0]: vertical.append((entry, exit))
if len(left) > 0: adj.append(left[-1]) if len(right) > 0: adj.append(right[0]) if len(up) > 0: adj.append(up[-1]) if len(down) > 0: adj.append(down[0]) adj += [lu, ru, ld, rd] if data[i, j] == 'L' and adj.count('#') == 0: grid[i, j] = '#' elif data[i, j] == '#' and adj.count('#') >= 5: grid[i, j] = 'L' if (data == grid).all(): return grid else: return get_final_layout2(grid) data_part1 = np.pad(np.array([[j for j in i] for i in get_input()]), (1, 1)) data_part2 = np.array([[j for j in i] for i in get_input()]) part1 = np.count_nonzero(get_final_layout1(data_part1) == '#') part2 = np.count_nonzero(get_final_layout2(data_part2) == '#') print(f'Result {part1}') print(f'Result {part2}')
import aoc_helper data = aoc_helper.get_input("4", "plain") data_split = data.split("\n\n") numbers = [int(num) for num in data_split[0].split(",")] # print(numbers) # Skipt first and last entry to get our raw bingo board data boards = [[[int(col) for col in row.split()] for row in board] for board in [line.split("\n") for line in data_split[1:-1]]] # print(boards) # for board in boards: # print(board) # for row in board: # print(row.split()) # print(boards) ROWS = len(boards[0]) COLS = len(boards[0][0]) # print(ROWS, COLS) def is_winner(board, numbers): # Check all in a row for c in range(COLS): row_count = 0 for r in range(ROWS): if board[c][r] not in numbers: break else:
# -*- coding: utf-8 -*- """ Created on Fri Dec 11 05:59:32 2020 @author: gape """ from collections import Counter import re import aoc_helper data = aoc_helper.get_input(11, force=True).strip() # data = aoc_helper.get_input(11).strip() print('Day 11 input (first 10 lines):') print('\n'.join(data.split('\n')[:10])) print('\nTotal input length: ', len(data)) print('Total input row count: ', len(data.split('\n'))-1) print("\n############################################################\n") def count1(i_s, j_s, data): cnt = 0 for j in range(j_s-1, j_s+2): if j < 0 or j > len(data)-1: continue else: row = data[j] for i in range(i_s-1, i_s+2): if i < 0 or i > len(row)-1 or (j==j_s and i==i_s): continue
# -*- coding: utf-8 -*- import aoc_helper data = aoc_helper.get_input(1) print('Day 1 input:') print(data) print('Total input length: ', len(data)) print('Total input row length: ', len(data.split())) print() data = [int(d) for d in data.split()] done = False for i in data: for j in data: if i + j == 2020: print("Part 1 answer: ", i * j) done = True break if done: break d1 = sorted(data) done = False for i in range(len(d1)): for j in range(i, len(d1)): if d1[i] + d1[j] > 2020: break for k in range(j, len(d1)):
# -*- coding: utf-8 -*- """ Created on Sun Dec 12 18:12:04 2021 @author: gape """ from collections import Counter, defaultdict import aoc_helper data = aoc_helper.get_input(12, year=2021).strip() print('Day 12 input:') print(data[:200]) print('Total input length: ', len(data)) print('Total input row length: ', len(data.split())) print() def find(start, used, m, l): if start == 'end': return 1 s = 0 used = used.copy() used.add(start) for p in points[start]: if p.islower() and p in used: if p in ('start', 'end'): continue elif m < l: s += find(p, used, m+1, l) else:
import aoc_helper lines = aoc_helper.get_input("3", "string") DATA_LENGTH = len(lines[0]) def get_ones_and_zeros(lines): ones = [0 for _ in range(DATA_LENGTH)] zeros = [0 for _ in range(DATA_LENGTH)] # Part 1 for line in lines: i = 0 for char in line: # print(char) if int(char) == 1: ones[i] += 1 else: zeros[i] += 1 i += 1 return (ones, zeros) (ones, zeros) = get_ones_and_zeros(lines) # print(ones, zeros) gamma = "" epsilon = "" for i in range(DATA_LENGTH):