Ejemplo n.º 1
0
 def _parse_input(self, file: str):
     grid = []
     for i, line in enumerate(read_lines(file), start=1):
         grid.append([c for c in line])
         self.height = i
         self.width = len(line)
     self.grid = grid
Ejemplo n.º 2
0
def main(input_file: str) -> int:
    instructions = list(read_lines(input_file))

    memory_v1 = defaultdict(int)
    memory_v2 = defaultdict(int)
    mask = "X" * 36

    for line in instructions:
        if line.startswith("mask"):
            mask = read_mask(text=line)
        elif line.startswith("mem"):
            address, value = read_mem(text=line)
            memory_v1[address] = write_masked_value(value, mask)
            for floating_address in get_floating_addresses(
                    base_address=address, mask=mask):
                memory_v2[floating_address] = value
        else:
            raise RuntimeError

    print(
        f"Sum of all addresses is {sum(memory_v1.values())} (Using decoder v1)"
    )
    print(
        f"Sum of all addresses is {sum(memory_v2.values())} (Using decoder v2)"
    )

    return 0
Ejemplo n.º 3
0
def main(input_file: str) -> int:
    starting_numbers = [int(n) for n in list(read_lines(input_file))[0].split(",")]

    print("Starting numbers:", starting_numbers)
    memory_game(starting_numbers=starting_numbers, rounds=2020)
    memory_game(starting_numbers=starting_numbers, rounds=30000000)
    return 0
Ejemplo n.º 4
0
def main(input_file: str) -> int:
    data = list(int(line) for line in read_lines(input_file))
    invalid = find_invalid(data=data, preamble=25)
    print(f"{invalid} is invalid.")

    weakness = find_encryption_weakness(data=data, value=invalid)
    print(f"encryption weakness is {weakness}")
    return 0
Ejemplo n.º 5
0
def main(input_file: str) -> int:
    card_public, door_public = [int(k) for k in list(read_lines(input_file))]
    card_loop = find_loop_size(public_key=card_public)
    door_loop = find_loop_size(public_key=door_public)
    encryption_key = transform_subject_number(subject_number=door_public,
                                              value=1,
                                              loop=card_loop)
    print(f"Encryption key: {encryption_key}")
    return 0
Ejemplo n.º 6
0
def parse_input(file: str):
    lines = list(read_lines(file))
    index = lines.index("")

    for line in lines[:index]:
        key, value = line.split(":")
        RULES[key] = value.strip()

    for line in lines[index+1:]:
        MESSAGES.append(line)
Ejemplo n.º 7
0
def parse_tiles(file: str) -> List[List[str]]:
    tiles = []
    for line in read_lines(file):
        i = 0
        instructions = []
        while i < len(line):
            chars = 2 if line[i] in ["n", "s"] else 1
            instructions.append(line[i:i + chars])
            i += chars
        tiles.append(instructions)
    return tiles
Ejemplo n.º 8
0
def main(input_file: str) -> int:
    for policy in Policy:
        passwords = []
        for line in read_lines(input_file):
            passwords.append(Password(text=line, policy=policy))

        valid_passwords = [p for p in passwords if p.valid]
        print(
            f"{len(valid_passwords)} out of {len(passwords)} are valid (using policy: {policy.value})"
        )

    return 0
Ejemplo n.º 9
0
def main(input_file: str) -> int:
    boarding_passes = []
    for line in read_lines(input_file):
        boarding_passes.append(BoardingPass(text=line))

    seat_ids = sorted([bp.seat_id for bp in boarding_passes])
    print(f"Highest seat ID is {max(seat_ids)}")

    for seat_id in seat_ids:
        if seat_id + 1 not in seat_ids:
            print(f"Seat ID {seat_id + 1} is missing.")
            break
    return 0
Ejemplo n.º 10
0
def main(input_file: str) -> int:
    number_list = [
        int(line) for line in read_lines(input_file) if is_int(line)
    ]

    for term_count in (2, 3):
        terms = find_terms(terms=number_list, sum_=2020, term_count=term_count)
        if terms is not None:
            terms_str = " * ".join([str(t) for t in terms])
            print(f"{terms_str} = {math.prod(terms)}")
        else:
            print(f"No {term_count} terms found that sum to 2020.")

    return 0
Ejemplo n.º 11
0
def main(input_file: str) -> int:
    groups = split_list(lst=list(read_lines(input_file)), separator="")

    union_count = 0
    for group in groups:
        union = union_lists(*group)
        union_count += len(union)

    intersection_count = 0
    for group in groups:
        intersection = intersect_lists(*group)
        intersection_count += len(intersection)

    print(f"Sum of all counts is {union_count} (Union)")
    print(f"Sum of all counts is {intersection_count} (Intersection)")
    return 0
Ejemplo n.º 12
0
def get_tiles(file: str) -> List[Tile]:
    tiles = []

    lines = list(read_lines(file_path=file))
    indicies = [i for i, line in enumerate(lines) if line.startswith("Tile")]
    for i in range(len(indicies)):
        if i == len(indicies) - 1:
            slice = lines[indicies[i]:]
            name = slice[0]
            image = slice[1:]
        else:
            slice = lines[indicies[i]:indicies[i + 1]]
            name = slice[0]
            image = slice[1:-1]
        tiles.append(Tile(name=name, image=image))

    return tiles
Ejemplo n.º 13
0
def parse_input(file: str) -> Tuple[List[Rule], List[int], List[List[int]]]:
    sections = []
    section = []
    for line in read_lines(file):
        if line == "":
            sections.append(section)
            section = []
            continue
        section.append(line)
    sections.append(section)

    rules = []
    for line in sections[0]:
        rules.append(Rule(rules_text=line))
    your_ticket = [int(i) for i in sections[1][1].split(",")]
    nearby_tickets = [[int(i) for i in t.split(",")] for t in sections[2][1:]]

    return rules, your_ticket, nearby_tickets
Ejemplo n.º 14
0
def get_passport_list(file: str) -> List[Passport]:
    passports = list()

    # Group lines
    line_groups = []
    text_group = []
    for line in read_lines(file_path=file):
        if line == "":
            line_groups.append(text_group)
            text_group = []
            continue
        else:
            text_group.append(line)

    if len(text_group):
        # Last group
        line_groups.append(text_group)

    for text_group in line_groups:
        passport_data_text = " ".join(text_group)
        passports.append(Passport(text=passport_data_text))

    return passports
Ejemplo n.º 15
0
def parse_input(input_file: str) -> Tuple[int, List]:
    time = int(list(read_lines(input_file))[0])
    ids = list(read_lines(input_file))[1].split(",")
    return time, ids
Ejemplo n.º 16
0
 def _parse_input_file(self, file: str):
     for line in read_lines(file):
         self._bags.append(Bag(rule_text=line))
Ejemplo n.º 17
0
def main(input_file: str) -> int:
    for line in read_lines(input_file):
        pass
    return 0
Ejemplo n.º 18
0
 def _parse_input(self, file: str):
     lines = list(read_lines(file))
     for j, row in enumerate(lines):
         for i, cube in enumerate(row):
             if cube == ACTIVE:
                 self.active_cubes.add(Vector4(i, j, 0, 0))
Ejemplo n.º 19
0
def parse_input(file: str) -> List:
    lines = list(read_lines(file))
    return [int(c) for c in lines[0]]
Ejemplo n.º 20
0
 def _parse_input_file(self, file: str):
     for line in read_lines(file):
         self.rows.append(line)
         if len(line) > self.width:
             self.width = len(line)
Ejemplo n.º 21
0
def parse_decks(file: str) -> Tuple[List, List]:
    lines = list(read_lines(file_path=file))
    index = lines.index("")
    deck_1 = lines[1:index]
    deck_2 = lines[index + 2:]
    return deck_1[::-1], deck_2[::-1]
Ejemplo n.º 22
0
 def load_instructions(self, file: str):
     self.instructions = []
     for line in read_lines(file):
         self.instructions.append(Instruction.from_text(text=line))
Ejemplo n.º 23
0
def parse_instructions(input_file: str) -> Generator[Tuple[str, int]]:
    for line in read_lines(input_file):
        yield line[0], int(line[1:])