Example #1
0
def get_numbers(filepath):
    data = []
    for line in utils.read_lines(filepath):
        num = line.strip()
        if num:
            data.append(int(num))
    return data
Example #2
0
def parse(filename: str) -> List[int]:
    octopi = []

    for line in utils.read_lines(filename, True):
        octopi.extend([int(n) for n in line])

    return octopi
Example #3
0
def part_one(filepath, slope):
    tree_count = 0
    for line_num, line in enumerate(utils.read_lines(filepath, strip=True)):
        index = get_index(len(line), line_num, slope)
        if index != -1 and is_tree(line[index]):
            tree_count += 1
    return tree_count
Example #4
0
def parse(filename: str) -> Tuple[List[int], int]:
    values = []
    width = -1
    for line in utils.read_lines(filename, True):
        values.extend([int(value) for value in line])
        width = len(line)
    return values, width
Example #5
0
def parse(
    filename: str
) -> Generator[Tuple[Tuple[int, int], Tuple[int, int]], None, None]:
    for line in utils.read_lines(filename, True):
        start, end = [point.strip() for point in line.split("->")]
        yield tuple([
            tuple(int(value) for value in start.split(",")),
            tuple(int(value) for value in end.split(","))
        ])
Example #6
0
def syntax_score(filename: str) -> None:
    checkers = []
    for line in utils.read_lines(filename, True):
        checkers.append(SyntaxChecker(line))

    total = 0
    for checker in checkers:
        checker.process()
        if checker.line_status == LineStatus.corrupted:
            total += checker.illegal_character_score
    print(total)
Example #7
0
def build_graph(filepath):
    graph = DirectedGraph()
    for line in utils.read_lines(filepath):
        bag, children = get_bags(line)
        graph.add_node(bag)
        for child in children:
            (count, name) = child
            graph.add_node(name)
            graph.add_child(bag, name, count)
            graph.add_parent(name, bag)
    return graph
Example #8
0
def part_one_and_two(filpath):
    sled_count = 0
    santa_count = 0
    for line in utils.read_lines(filepath):
        rule_part, pwd_part = line.split(":")
        rule = Rule.from_rule_str(rule_part)
        if rule.is_valid_password_for_sled(pwd_part.strip()):
            sled_count += 1
        if rule.is_valid_password_for_santa(pwd_part.strip()):
            santa_count += 1
    return sled_count, santa_count
Example #9
0
def part_one(filepath):
    sum = 0
    group = ""
    for line in utils.read_lines(filepath, strip=True):
        if line:
            group += line
        else:
            sum += len(set(char for char in group))
            group = ""
    sum += len(set(char for char in group))
    return sum
Example #10
0
def part_two(filepath):
    sum = 0
    group = []
    for line in utils.read_lines(filepath, strip=True):
        if line:
            group.append(set(char for char in line))
        else:
            sum += len(reduce(lambda x, y: x.intersection(y), group))
            group = []
    sum += len(reduce(lambda x, y: x.intersection(y), group))
    return sum
Example #11
0
def part_one_and_two(filepath, rules):
    total_valid = 0
    regex = re.compile(get_regex(*rules))
    passport_lines = []
    for line in utils.read_lines(filepath, strip=True):
        if line:
            passport_lines.append(line)
        else:
            total_valid += int(is_valid_passpord(passport_lines, regex))
            passport_lines = []
    total_valid += int(is_valid_passpord(passport_lines, regex))
    return total_valid
Example #12
0
def parse(filename: str) -> Tuple[str, Dict[str, str]]:
    template = ""
    insertion_pairs = {}

    for line in utils.read_lines(filename, True):
        if line:
            parts = line.split("->")
            if len(parts) == 1:
                template = parts[0].strip()
            else:
                insertion_pairs[parts[0].strip()] = parts[1].strip()
    return template, insertion_pairs
Example #13
0
def part_two(filepath):
    double_pairs = re.compile(r"([a-z][a-z]).*\1")
    skip_letter = re.compile(r"([a-z]).{1}\1")

    valid_count = 0

    for line in utils.read_lines(filepath, strip=True):
        has_double_pairs = double_pairs.search(line) is not None
        has_skip_letter = skip_letter.search(line) is not None
        if has_double_pairs and has_skip_letter:
            valid_count += 1

    return valid_count
Example #14
0
def autocomplete_score(filename: str) -> None:
    checkers = []
    for line in utils.read_lines(filename, True):
        checkers.append(SyntaxChecker(line))

    scores = []
    for checker in checkers:
        checker.process()
        if checker.line_status == LineStatus.incomplete:
            scores.append(checker.autocomplete_score)

    scores.sort()
    print(scores[int(len(scores) / 2)])
Example #15
0
def part_one(filepath):
    double_letters = re.compile(r"(.)\1{1,}")
    three_vowels = re.compile(r"^(.*[aeiou].*){3,}$")
    does_not_have = re.compile(r"^((?!ab|cd|pq|xy).)*$")

    valid_count = 0

    for line in utils.read_lines(filepath, strip=True):
        has_double_letters = double_letters.search(line) is not None
        has_three_vowels = three_vowels.search(line) is not None
        has_does_not_have = does_not_have.search(line) is not None
        if has_double_letters and has_three_vowels and has_does_not_have:
            valid_count += 1

    return valid_count
Example #16
0
def parser(
        filename: str) -> Tuple[Tuple[int, ...], Tuple[Tuple[int, ...], ...]]:
    guesses = None
    boards = []
    current_board = []
    for line in utils.read_lines(filename, True):
        if guesses is None:
            guesses = tuple(int(value) for value in line.split(","))
            continue
        if line:
            current_board.extend([int(value) for value in line.split()])
        elif not line and current_board:
            boards.append(tuple(board for board in current_board))
            current_board = []
    boards.append(tuple(board for board in current_board))

    return guesses, tuple(boards)
Example #17
0
def window_depth_changes(filename: str, window_size: int) -> tuple:
    depth_map = []

    current_window_values = []
    previous = None
    for line in utils.read_lines(filename):
        if line:
            current_window_values.append(int(line))

            if len(current_window_values) == window_size:
                total = sum(current_window_values)
                if previous is None or previous == total:
                    change = 0
                else:
                    change = 1 if total > previous else -1
                depth_map.append((total, change))
                previous = total
                current_window_values.pop(0)

    return tuple(depth_map)
Example #18
0
    def execute(self, filepath, attempt_fix):
        env = RuntimeEnvironment()
        lines = []
        for line in utils.read_lines(filepath):
            operation, argument = line.split(" ")
            lines.append([operation, int(argument)])

        try:
            return self._execute(lines, env)
        except InterpreterInfiniteLoopError:
            print("Infinite loop found.")
            if attempt_fix:
                print("Attempting to auto-fix.")
                fixed_env = self.attempt_fix(lines, env.executed_lines)
                if fixed_env:
                    print("Successfully auto-fixed program.")
                    return fixed_env.accumulator
                else:
                    print("Failed to auto-fix program.")
            print("Exiting interpreter and returning partially completed runtime accumulator value.")
            return env.accumulator
Example #19
0
    def __init__(self, filename: str) -> None:
        self.width = 0
        self.height = 0

        self._by_row = defaultdict(set)
        self._by_col = defaultdict(set)
        self._instructions = []

        for line in utils.read_lines(filename, True):
            if line:
                parts = line.split(",")
                if len(parts) == 2:
                    x, y = int(parts[0]), int(parts[1])
                    if x + 1 > self.width:
                        self.width = x + 1
                    if y + 1 > self.height:
                        self.height = y + 1
                    self._by_row[y].add(x)
                    self._by_col[x].add(y)
                else:
                    parts = line.split("=")
                    self._instructions.append(
                        (parts[0].split(" ")[-1], int(parts[1])))
Example #20
0
        co2 = self._filter_co2()[0]

        oxy = int(oxy, 2)
        co2 = int(co2, 2)
        return oxy, co2

    def get_power_consumption(self) -> int:
        return reduce(lambda x, y: x * y,
                      self._get_gamma_and_sigma(self.values))

    def get_life_support_rating(self) -> int:
        return reduce(lambda x, y: x * y, self._get_oxygen_and_co2())


if __name__ == "__main__":
    test_filename = "2021/03-test.txt"
    filename = "2021/03.txt"

    test_values = [
        line for line in utils.read_lines(test_filename, True) if line
    ]
    values = [line for line in utils.read_lines(filename, True) if line]

    test_diag = Diagnostic(test_values)
    print(f"Test Power: {test_diag.get_power_consumption()}")
    print(f"Test Life: {test_diag.get_life_support_rating()}")

    diag = Diagnostic(values)
    print(f"Real Power: {diag.get_power_consumption()}")
    print(f"Real Life: {diag.get_life_support_rating()}")
Example #21
0
def parse(filename: str) -> Matrix:
    data = []
    for line in utils.read_lines(filename, True):
        data.append(tuple(int(x) for x in line))
    return tuple(data)
Example #22
0
def parse(filename: str):
    for line in utils.read_lines(filename, True):
        signal, output = tuple(x.strip() for x in line.split("|"))
        yield tuple(s for s in signal.split(" ")), tuple(
            o for o in output.split(" "))
Example #23
0
def get_directions(filename: str) -> Tuple[Direction, int]:
    for line in utils.read_lines(filename):
        direction, amount = line.split(" ")
        yield (Direction(direction), int(amount))
Example #24
0
def get_presents(filepath):
    for line in utils.read_lines(filepath):
        length, width, height = line.split("x")
        yield Present(length=int(length), width=int(width), height=int(height))