def part_1(): position = [0, 0] facing = "E" print("Initial:", position[X], position[Y], facing) lines = AOC.get_input_lines(12, AOC.format_strip) for line in lines: action = str(line[:1]) value = int(line[1:]) if action in compass_str: position[X] += compass[action][X] * value position[Y] += compass[action][Y] * value if action == "F": position[X] += compass[facing][X] * value position[Y] += compass[facing][Y] * value if action in rotate_str: steps = int(int(rotation[action] * value) / 90) total_steps = len(compass_str) facing = compass_str[(total_steps + compass_str.find(facing) + steps) % total_steps] print("Position: {},{} Direction: {}".format(position[X], position[Y], facing)) print("Manhattan Distance:", abs(position[X]) + abs(position[Y]))
def part_2(): def rotate_90(xy: [], clockwise: int) -> []: return [clockwise * xy[1], -clockwise * xy[0]] ship = [0, 0] waypoint_relative = [10, 1] print("Initial:", ship[X], ship[Y]) lines = AOC.get_input_lines("12", AOC.format_strip) for line in lines: action = str(line[:1]) value = int(line[1:]) if action in compass_str: waypoint_relative[X] += compass[action][X] * value waypoint_relative[Y] += compass[action][Y] * value if action == "F": ship[X] += waypoint_relative[X] * value ship[Y] += waypoint_relative[Y] * value if action in rotate_str: for _ in range(0, int(int(abs(rotation[action]) * value) / 90)): waypoint_relative = rotate_90(waypoint_relative, rotation[action]) print("Position: {},{} Waypoint: {} {}".format(ship[X], ship[Y], waypoint_relative[X], waypoint_relative[Y])) print("Manhattan Distance:", abs(ship[X]) + abs(ship[Y]))
def part_2(): lines = AOC.get_input_lines("11", AOC.format_strip) old_seats = [] for line in lines: old_seats.append(list(line)) anything_changed = True while anything_changed: new_seats = [x[:] for x in old_seats] anything_changed = False for y in range(0, len(old_seats)): for x in range(0, len(old_seats[y])): if old_seats[y][x] != FLOOR: new_seat = occupy_seat_part2(x, y, old_seats) if new_seat != new_seats[y][x]: new_seats[y][x] = new_seat anything_changed = True old_seats = [x[:] for x in new_seats] print("Final:") for row in range(0, len(new_seats)): print("".join(new_seats[row])) print("") print("Occupied:", count_occupied(new_seats)) return
def part_2(): def for_calculate(buses : []): # buses = [(17,0),(13,2),(19,3)] print(buses) STEP = 0 OFFSET = 1 time = 0 step = buses[0][STEP] for i in range(1, len(buses)): while not (time + buses[i][OFFSET]) % buses[i][STEP] == 0: time += step step *= buses[i][STEP] print("Result:", time) lines = AOC.get_input_lines("13", AOC.format_strip) slots = lines[1].split(",") buses = [] for i in range(0, len(slots)): if slots[i] != "x": buses.append((int(slots[i]),i)) print("Buses: {}".format(buses)) for_calculate(buses)
def part_1(): lines = AOC.get_input_lines(14, AOC.format_strip) full_memory = {} current_mask = int_to_bits(0) for line in lines: # Mask setter if "mask = " in line: current_mask = line.replace("mask = ", "") # Memory setter if "mem" in line: mem_index = int(line.replace("mem" + "[", "").partition("] = ")[0]) mem_value = int(line.replace("mem" + "[", "").partition("] = ")[2]) full_memory[mem_index] = apply_mask(current_mask, int_to_bits(mem_value)) total = 0 for value in full_memory.keys(): total += bits_to_int(full_memory[value]) print("Total:", total) return
def get_code() -> []: lines = AOC.get_input_lines(8, AOC.format_strip) code = [] for line in lines: line.replace("+","") split = line.split(" ") code.append(split) return code
def part_1(): lines = AOC.get_input_lines(15, AOC.format_strip) numbers = lines[0].split(",") # part_1 total_count = 2020 # part_2 total_count = 30000000 # test #numbers = ["0","3","6"] #total_count = 10 turn = 1 spoken = [] spoken_history = {} def add_or_append_history(number: str): if number in spoken_history.keys(): spoken_history[number].append(turn) else: spoken_history[number] = [turn] for number in numbers: spoken.append(number) add_or_append_history(number) turn += 1 while turn <= total_count: number = 0 if len(spoken_history[spoken[-1]]) > 1: number = spoken_history[spoken[-1]][-1] - spoken_history[ spoken[-1]][-2] # print("Turn {}, Number {}, Repeat {}".format(turn, number, last_was_repeat)) spoken.append(str(number)) add_or_append_history(str(number)) if turn % 10000000 == 0: print(turn, float(turn) / 30000000, "%") turn += 1 print("Spoken:", spoken) print("Last:", spoken[-1])
def part_1(): lines = AOC.get_input_lines(6, AOC.format_strip) groups = [] current_group = "" for line in lines: if line == "": groups.append(current_group) current_group = "" else: for c in line: if c not in current_group: current_group += c groups.append(current_group) return groups
def part_1(): lines = AOC.get_input_lines("10", AOC.format_to_int) lines.sort() diffs = [0, 0, 0] diffs[lines[0] - 1] += 1 # outlet to first adapter for i in range(0, len(lines) - 1): diff = lines[i + 1] - lines[i] diffs[diff - 1] += 1 diffs[2] += 1 # last adapter to device print("Diffs:", diffs) print("Result: ", diffs[0] * diffs[2])
def main(): start = time.time() data = AOC.Advent(2020,3).input_data matrix = [line.replace('#','1').replace('.','0') for line in data] matrix = [[int(value) for value in row] for row in matrix] def slope(horizontal, vertical): trees = 0 for i in range( int( len(matrix) / vertical // 1 ) ): trees += matrix[vertical * i][horizontal * i % len(matrix[0])] return trees if __name__ == "__main__": print("The solution to problem 1 is: {}".format(slope(3,1))) print("The solution to problem 2 is: {}".format(slope(1,1) * slope(3,1) * slope(5,1) * slope(7,1) * slope(1,2))) print('Completed in {} seconds.'.format(time.time() - start))
def part_2(): lines = AOC.get_input_lines(14, AOC.format_strip) full_memory = {} current_mask = int_to_bits(0) for line in lines: # Mask setter if "mask = " in line: current_mask = line.replace("mask = ", "") # print(current_mask) # Memory setter if "mem" in line: mem_index = int(line.replace("mem" + "[", "").partition("] = ")[0]) mem_value = int(line.replace("mem" + "[", "").partition("] = ")[2]) base_address = int_to_bits(mem_index) masked_address = apply_mask_v2(current_mask, base_address) # print(masked_address) addresses = [] def generate_floating_addresses(from_address: str) -> []: if from_address.find("X") != -1: new_0 = from_address.replace("X", "0", 1) new_1 = from_address.replace("X", "1", 1) generate_floating_addresses(new_0) generate_floating_addresses(new_1) else: addresses.append(from_address) generate_floating_addresses(masked_address) # print(addresses) for address in addresses: full_memory[address] = mem_value total = 0 for value in full_memory.keys(): total += full_memory[value] print("Total:", total) return
def part_1(): lines = AOC.get_input_lines(13, AOC.format_strip) earliest_timestamp = int(lines[0]) buses = list(map(int, lines[1].replace(",x","").split(","))) print(earliest_timestamp) print(buses) best_wait = -1 best_bus = -1 for bus in buses: wait = -(earliest_timestamp % bus) + bus print("Bus {} Wait {}".format(bus, wait)) if wait < best_wait or best_wait == -1: best_wait = wait best_bus = bus print("Result: ", best_bus * best_wait)
def part_2(): lines = AOC.get_input_lines(6, AOC.format_strip) groups = [] current_group = "" new_line = True for line in lines: if line == "": groups.append(current_group) current_group = "" new_line = True else: if new_line: current_group = line new_line = False else: test_group = current_group for c in test_group: if c not in line: current_group = current_group.replace(c, "") groups.append(current_group) return groups
def check_passports(): lines = AOC.get_input_lines(4, AOC.format_strip) # generate passports passports = [] passport_entries = [] for line in lines: if (line == ""): passports.append(passport_entries[:]) passport_entries.clear() else: chunks = line.split() for chunk in chunks: passport_entries.append(chunk) passports.append(passport_entries) # generate passport requirements def in_range(value: str, min: int, max: int): return int(value) >= min and int(value) <= max def pass_hgt(value: str): if ("cm" in value): return in_range(value.replace("cm", ""), 150, 193) elif ("in" in value): return in_range(value.replace("in", ""), 59, 76) return False def pass_hcl(value: str): if (value[0] == "#"): if (len(sub := value.replace("#", "")) == 6): for c in sub: if (c not in "0123456789abcdef"): return False return True return False
import AOC INACTIVE = False ACTIVE = True X = 0 Y = 1 Z = 2 W = 3 STATE = 0 DESIRED = 1 input = "17" # 17 lines = AOC.get_input_lines(input, AOC.format_strip) for line in lines: print(line) def text_to_dimension(input: []) -> {}: dimension = {} for i, line in enumerate(lines): y = i for j, char in enumerate(line): x = j z = 0 w = 0 dimension[(x, y, z,
import AOC import time AOC.Advent(2020, 6) with open('input/input06.txt') as f: data = f.readlines() data = ''.join(data).split('\n\n') def main(): def count(group: str) -> int: s = set('a b c d e f g h i j k l m n o p q r s t u v w x y z'.split()) for question in group.split(): s = s.intersection(set(question)) return len(s) if __name__ == "__main__": print("The solution to problem 1 is: {}".format( sum((len(set(i.replace('\n', ''))) for i in data)))) print("The solution to problem 2 is: {}".format( sum(count(group) for group in data))) start = time.time() main() print('Completed in {} seconds.'.format(time.time() - start))
from typing import List import sys sys.path.insert(1, sys.path[0] + '/..') # Add parent of my directory to path import AOC ## pylint: disable=import-error lines: List = AOC.loadInput(None,'input', notInt=True) TEST = ["00100", "11110", "10110", "10111", "10101", "01111", "00111", "11100", "10000","11001","00010", "01010" ] def part1(input: List) -> int: bits = [int(a) for a in "0" * len(str(input[0]))] sbits = [int(a) for a in "0" * len(str(input[0]))] ubits = [int(a) for a in "0" * len(str(input[0]))] for line in input: for n,bit in enumerate(str(line)): bits[n] += int(bit) half = len(input)/2 for n,a in enumerate(bits): if a > half: sbits[n] = 1 ubits[n] = 0 else: sbits[n] = 0 ubits[n] = 1 gamma = int("".join([str(a) for a in sbits]),2) epsilon = int("".join([str(a) for a in ubits]),2) print(sbits, gamma) print(ubits, epsilon) return gamma*epsilon
#!/usr/bin/env python import sys sys.path.insert(1, sys.path[0] + '/..') # Add parent of my directory to path from itertools import combinations import AOC ## pylint: disable=import-error lines = AOC.loadInput(9) preamble = 25 def xmas_check(num, buffer): for a, b in combinations(buffer, 2): if a + b == num: return True return False def xmas_hack(num, buffer): for start in range(len(buffer)): offset = 2 while sum(buffer[start:start + offset]) < num: offset += 1 if sum(buffer[start:start + offset]) == num: # print(buffer[start:start+offset]) # print(f"fount at {start} - {start+offset}") _min = min(buffer[start:start + offset]) _max = max(buffer[start:start + offset]) print(f"{_min} + {_max} = {_min+_max}") return
import AOC import itertools inp = AOC.read_input() mems = inp.split('\n')[:-1] def apply_mask(val): new_bin = [] bin_val = bin(int(val))[2:] bin_val = '0' * (len(mask) - len(bin_val)) + bin_val l = 0 for i in range(len(mask)): if mask[i] == 'X': l += 1 new_bin.append('{}') elif mask[i] == '0': new_bin.append(bin_val[i]) else: new_bin.append(mask[i]) return [ ''.join(new_bin).format(*i) for i in itertools.product('01', repeat=l) ] addrs = [] vals = [] for i in mems: if i.startswith('mask'): mask = i.split(' ')[-1]
#!/usr/bin/env python import itertools import sys import math from functools import reduce sys.path.insert(1, sys.path[0] + '/..') # Add parent of my directory to path import AOC ## pylint: disable=import-error lines = AOC.loadInput(None, 'day13.data') times = lines[1].split(',') #Bruteforcetime # >>> gcd(3420,19) # 19 # >>> gcd(3419,13) # 13 # >>> gcd(3417,17) # 17 maxnum = sorted([int(x) for x in times if x.isdigit()]) nogcd = False cmp = maxnum[-1] maxstep = reduce((lambda x, y: x * y), maxnum) print(cmp, maxstep) while True: for i, a in enumerate(times): if a == 'x' or nogcd: next elif math.gcd(cmp + i, int(a)) == int(a): if i > 11:
import AOC AOC.Advent(2020, 1) def main(): with open('input/input01.txt') as f: expense = [int(i) for i in f.read().splitlines()] def loopsum(looplist, val=2020) -> int: for index, item1 in enumerate(looplist): for item2 in looplist[index:]: if item1 + item2 == val: return item1, item2 def loopsum2(looplist, val=2020) -> int: for idx1, item1 in enumerate(looplist): for idx2, item2 in enumerate(looplist[idx1:]): for item3 in looplist[idx2:]: if item1 + item2 + item3 == val: return item1, item2, item3 if __name__ == "__main__": item1, item2 = loopsum(expense) print("The solution to problem 1 is: {}".format(item1 * item2)) item1, item2, item3 = loopsum2(expense) print("The solution to problem 2 is: {}".format(item1 * item2 * item3)) main()
test_total = lines[current_index] while test_total < target: current_index += 1 test_total += lines[current_index] if target == test_total: print("Found sum values:", lines[i:current_index + 1]) min = 0 max = 0 for value in lines[i:current_index + 1]: if value < min or min == 0: min = value if value > max or max == 0: max = value print("Min:", min, "Max:", max) print("Result:", min + max) return print("ERROR no sum found") return # Main lines = AOC.get_input_lines(9, AOC.format_to_int) part_1(lines) part_2(lines)
def part_2(): def find_jump_indices(i: int, all: []) -> []: jump_indices = [] if (test := i + 1) < len(all): if all[test] - all[i] <= 3: jump_indices.append(test) if (test := i + 2) < len(all): if all[test] - all[i] <= 3: jump_indices.append(test) if (test := i + 3) < len(all): if all[test] - all[i] <= 3: jump_indices.append(test) return jump_indices lines = AOC.get_input_lines("10", AOC.format_to_int) lines.sort() lines.insert(0, 0) lines.append(lines[len(lines) - 1] + 3) # TEST # lines = [0,1,2,3,6] print(lines) branches_from_here = [0] * len(lines) branches_from_here[len(lines) - 1] = 1 for current_index in range((len(lines) - 1), -1, -1): indices = find_jump_indices(current_index, lines)
#!/usr/bin/env python from functools import lru_cache import itertools import sys sys.path.insert(1, sys.path[0] + '/..') # Add parent of my directory to path import AOC ## pylint: disable=import-error lines = AOC.loadInput(None,'day11.data') class Seating(): def __init__(self,world): self.world = world self.occ = 0 self.maxx = len(self.world)-1 self.maxy = len(self.world[0])-1 self.checkmatrix = list(filter(self.not00, itertools.product((1,0,-1),repeat=2))) def not00(self, x): return x != (0,0) def seecheck(self,x,y,dx,dy): ddx = dx ddy = dy while True: if 0 <= x+dx <= self.maxx: if 0 <= y+dy <= self.maxy: if self.world[x+dx][y+dy] == ".": dx += ddx dy += ddy next elif self.world[x+dx][y+dy] == "#":
import AOC import time data = AOC.Advent(2020,5).input_data def main(): def seat_number(id): row, col = id[:7], id[7:] row = int(row.replace('B','1').replace('F','0'), 2) col = int(col.replace('L','0').replace('R','1'), 2) return 8 * row + col x = {seat_number(line) for line in data} if __name__ == "__main__": print("The solution to problem 1 is: {}".format(max(x))) print("The solution to problem 2 is: {}".format( set(range(min(x), max(x)+1)) - x )) start = time.time() main() print('Completed in {} seconds.'.format(time.time() - start))
from typing import List import sys sys.path.insert(1, sys.path[0] + '/..') # Add parent of my directory to path import AOC ## pylint: disable=import-error lines: List = AOC.loadInput(None, 'input') TEST = ["forward 5", "down 5", "forward 8", "up 3", "down 8", "forward 2"] def part1(input: List) -> int: horizontal = 0 depth = 0 for data in input: cmd, length = data.split() length = int(length) if cmd == "forward": horizontal += length elif cmd == "down": depth += length elif cmd == "up": depth -= length return horizontal * depth def part2(input: List) -> int: horizontal = 0 depth = 0 aim = 0 for data in input: cmd, length = data.split() length = int(length)