Ejemplo n.º 1
0
from lib import open_file
import re

rules = open_file("7/input")
rules_dict = {}

for rule in rules:
    bags, contain = rule.split("contain")
    contain_list = [
        bag.replace("bags", "").replace("bag", "").replace(".", "").strip()
        for bag in contain.split(", ")
    ]
    value = []
    for bag in contain_list:
        nb, name = 0, ""
        try:
            info = bag.split(" ")
            nb = int(info[0])
            name = " ".join(info[1:])
        except:
            nb, name = 0, bag.split(" ")[0]
        value.append((nb, name))
    rules_dict[bags.replace("bags", "").strip()] = value

char_regex = re.compile("[a-z]+")


def bag_contain_gold(bag_contain):
    for bag in bag_contain:
        _, name = bag
        if name == "shiny gold":
Ejemplo n.º 2
0
from lib import open_file

numbers = open_file("9/input")
numbers = [int(num) for num in numbers]


def property_checker(preamble, nb):
    for elt in preamble:
        if nb-elt in preamble:
            return True
    return False


def find_nb_not_matching(n):
    idx = 0
    while idx < len(numbers):
        preamble = set(numbers[idx:idx+n])
        nb = numbers[idx + n]
        if not property_checker(preamble, nb):
            return nb, idx+n
        idx += 1


def find_encryption_weakness():
    target, idx = find_nb_not_matching(25)
    candidate_nbs = set()
    i = idx-1
    cursor = i
    while 0 < i:
        candidate_res = sum(nb for nb in candidate_nbs)
        if candidate_res == target:
Ejemplo n.º 3
0
from lib import open_file
import sys
try:
    if sys.argv[1] == "--sample":
        instructions = open_file("12/sample")
except:
    instructions = open_file("12/input")

directions = ("E", "S", "W", "N")
current = {"E": 0, "N": 0}
facing = {"value": "E", "opposite": "W", "idx": 0}
waypoint = {"E": 10, "N": 1}
current_waypoint = {"E": 0, "N": 0}
waypoint_dirs = ("EN", "ES", "WS", "WN")


def manhattan_distance(current):
    res = 0
    for v in current.values():
        res += abs(v)
    return res


def move(direction, value, current_=current):
    to_add = value
    dir_idx = directions.index(direction)
    opposite = directions[(dir_idx+2) % 4]
    if opposite in current_:
        if current_[opposite] - value > 0:
            final_direction = opposite
            to_add = current_[opposite] - value
Ejemplo n.º 4
0
from lib import open_file

instructions = open_file("8/input")


def run(instructions):
    seen = set()
    acc = 0
    idx = 0
    infinite_loop = False
    while idx < len(instructions):
        opcode, value = instructions[idx].split()
        if idx in seen:
            infinite_loop = True
            break
        else:
            seen.add(idx)
        if opcode == "nop":
            idx += 1
            continue
        value = int(value)
        if opcode == "acc":
            acc += value
            idx += 1
        if opcode == "jmp":
            idx += value
    return (acc, infinite_loop, seen)


def find_acc(instructions, autofix=False):
    ins = instructions.copy()
Ejemplo n.º 5
0
from lib import open_file
from copy import deepcopy

seats = [list(elt) for elt in open_file("11/input")]


def get_adjeacents(x, y):
    return ((x, y + 1), (x + 1, y), (x, y - 1), (x - 1, y), (x - 1, y + 1),
            (x + 1, y + 1), (x - 1, y - 1), (x + 1, y - 1))


def check_adj_occupied1(x, y, seats):
    '''
    Return True when there is 4+ occupied adjeaceant seat around occupied
    seat(x,y)
    '''
    adjeacents = get_adjeacents(x, y)
    occupied = 0
    for seat in adjeacents:
        x, y = seat
        if x < 0 or y < 0 or x >= len(seats) or y >= len(seats[0]):
            continue
        if seats[x][y] == "#":
            occupied += 1
    return occupied


def check_adj_occupied2(x, y, seats):
    '''
    Return True when there is 5+ occupied adjeaceant seat around occupied
    seat(x,y)
Ejemplo n.º 6
0
from lib import open_file

nums = [int(n) for n in open_file("10/input")]
jolt_max = max(nums) + 3
nums.append(jolt_max)
nums.append(0)
nums.sort()


def find_jolt_diffs_nb(n, picked={}):
    nb = 0
    for num in nums:
        if num + n in nums:
            if num not in picked:
                nb += 1
                picked[num] = True
    return nb, picked


seen = {}


def distinct_arrangements_nb(jolt, jolt_low, jolt_hi):
    if jolt in seen:
        return seen[jolt]
    if jolt == jolt_max:
        seen[jolt] = 1
        return 1
    arrs = [elt for elt in nums if jolt_low <= elt - jolt <= jolt_hi]
    arrangements = 0
    for j in arrs:
Ejemplo n.º 7
0
from lib import open_file
import sys
try:
    if sys.argv[1] == "--sample":
        bus_info = open_file("13/sample")
    else:
        bus_info = open_file("13/input")
except:
    bus_info = open_file("13/input")

min_timestamp = int(bus_info[0])
bus_rules = bus_info[1].split(",")
buses_id = [int(elt) for elt in bus_rules if elt != "x"]
buses_id_part2 = [int(elt) if elt != "x" else 0 for elt in bus_rules]


def find_nearest_timestamp(min_timestamp, bus_id):
    res = bus_id
    while res < min_timestamp:
        res += bus_id
    return res


def get_nearest_timestamps(min_timestamp, buses_id):
    nearest_timestamps = {}
    for bus in buses_id:
        res = find_nearest_timestamp(min_timestamp, bus)
        nearest_timestamps[bus] = res
    return nearest_timestamps

Ejemplo n.º 8
0
from lib import open_file
import sys
import re
try:
    if sys.argv[1] == "--sample":
        exps = open_file("18/sample")
    else:
        exps = open_file("18/input")
except:
    exps = open_file("18/input")


def get_parenthesis(exp):
    ps = ""
    insert = False
    for e in exp:
        if e == "(":
            if insert:
                ps = ""
                continue
            insert = True
        elif e == ")":
            return ps
        elif insert:
            ps += e
    return ps

def replace_parenthesis(exp, addition_first=False):
    parenthesis = get_parenthesis(exp)
    while parenthesis:
        parenthesis_res = compute(parenthesis, addition_first)
Ejemplo n.º 9
0
from lib import open_file
import sys
try:
    if sys.argv[1] == "--sample":
        numbers = open_file("15/15.sample")
    else:
        numbers = open_file("15/15.input")
except:
    numbers = open_file("15/15.input")

numbers = [int(elt) for elt in numbers[0].split(",")]


def run(numbers, limit=2020):
    numbers = numbers.copy()
    seen = {number: idx for idx, number in enumerate(numbers)}
    last_spoken = numbers[-1]
    for i in range(len(numbers) - 1, limit - 1):
        seen[last_spoken], last_spoken = i, i - seen[
            last_spoken] if last_spoken in seen else 0
    return last_spoken


print("### PART 1")
print(run(numbers))
print("### PART 2")
print(run(numbers, 30000000))
Ejemplo n.º 10
0
from lib import open_file
import re

f = open_file("4/input")
# We add an ending empty string just for conveniance
f.append("")
passports = []
passport = {}
for elt in f:
    if elt:
        passport_elts = elt.split()
        for passport_elt in passport_elts:
            key, value = passport_elt.split(":")
            passport[key] = str(value)
    else:
        passports.append(passport)
        passport = {}

required_fields = ("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
ecl_possibilities = ("amb", "blu", "brn", "gry", "grn", "hzl", "oth")


def digits_regstring(n=4, add=""):
    base = r"^[0-9]{" + str(n) + "}"
    if add:
        base += add
    return base + "$"


def digits_regexp(n=4, add=""):
    return re.compile(digits_regstring(n, add))
Ejemplo n.º 11
0
from lib import open_file

seats = open_file("5/input")


def get_lower_bound_from_code(upp, code, symbol_low):
    low, upp = 0, upp
    for elt in code:
        if elt == symbol_low:
            upp = (upp + low) // 2
        else:
            low = (upp + low + 1) // 2
    return low


def get_row(row_code):
    return get_lower_bound_from_code(127, row_code, 'F')


def get_column(column_code):
    return get_lower_bound_from_code(7, column_code, 'L')


def get_info(code):
    row = get_row(code[:7])
    column = get_column(code[7:])
    seat_id = row * 8 + column
    return (row, column, seat_id)


seats_info = [get_info(seat) for seat in seats]
Ejemplo n.º 12
0
from lib import open_file

answers = open_file("6/input")
# For conveniance we add an empty string at the end of our answers
answers.append("")


def nb_questions_yes(group_answers, everyone=False):
    questions = {}
    for answers in group_answers:
        for answer in answers:
            if answer in questions.keys():
                questions[answer] += 1
            else:
                questions[answer] = 1
    if everyone:
        return sum(1 for answer in questions.keys() if questions[answer] == len(group_answers))
    else:
        return len(questions.keys())


res_anyone, res_everyone = 0, 0
group_answers = []
for answer in answers:
    if not answer:
        res_anyone += nb_questions_yes(group_answers)
        res_everyone += nb_questions_yes(group_answers, everyone=True)
        group_answers = []
    else:
        group_answers.append(answer)
Ejemplo n.º 13
0
from lib import open_file
from functools import lru_cache
import sys
try:
    if sys.argv[1] == "--sample":
        info = open_file("16/sample")
    else:
        info = open_file("16/input")
except:
    info = open_file("16/input")
ranges = {}
idx = 0
while idx < len(info):
    if not info[idx]:
        idx += 2
        break
    line = info[idx]
    key, v = line.split(":")
    v = v.split("or")
    value = []
    for r in v:
        a, b = r.strip().split("-")
        a, b = int(a), int(b)
        value.append((a, b))
    ranges[key] = value
    idx += 1

my_ticket = [int(elt) for elt in info[idx].split(",")]
idx += 3
nearby_tickets = []
for i in range(idx, len(info)):
Ejemplo n.º 14
0
import sys
from lib import open_file
from lib import DataSanitation
from lib import Database

if __name__ == '__main__':
    try:
        print(sys.argv[1])

        schema_file = r'C:\Users\userab\PycharmProjects\MomWorkHelper\schema.sql'
        db_file = r'C:\Users\userab\PycharmProjects\MomWorkHelper\test.db'

        raw = open_file(sys.argv[1])

        data = DataSanitation(raw)()

        database = Database(schema_file, db_file)
        for line in data:
            database.insert(line)

        print(f'TOTAL = {len(data)}')
        # input()

    except:
        import traceback
        traceback.print_exc()
        input()
Ejemplo n.º 15
0

def check(policy, password):
    low, upp, letter = policy_splitter(policy)
    occ = password.count(letter)
    if occ >= low and occ <= upp:
        return True
    return False


def new_check(policy, password):
    low, upp, letter = policy_splitter(policy)
    return (password[low] == letter) ^ (password[upp] == letter)


lines = open_file("2/input")
# PART 1
res = 0
for line in lines:
    policy, password = line.split(":")
    if check(policy, password):
        res += 1
print("### Part1")
print(res)

# PART 2
res = 0
for line in lines:
    policy, password = line.split(":")
    if new_check(policy, password):
        res += 1
Ejemplo n.º 16
0
from lib import open_file

lines = open_file("3/input")

_map = []
for line in lines:
    __map = []
    for square in line:
        __map.append(square)
    _map.append(__map)


def countTrees(right, down):
    map_width = len(_map[0])
    map_height = len(_map)
    cur_y = down
    cur_x = (0 + right) % (map_width)
    trees = 0
    while cur_y < map_height:
        if _map[cur_y][cur_x] == "#":
            trees += 1
        cur_x = (cur_x + right) % (map_width)
        cur_y = cur_y + down
    return trees


print("### PART 1")
print(countTrees(3, 1))
dirs = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
res = 1
for d in dirs: