Пример #1
0
        original_command = command_list[i]
        cmd_type, num = parse_command(original_command)
        if cmd_type == "acc":
            continue
        command_list[i] = toggle_nop_jmp(original_command)
        yield command_list
        command_list[i] = original_command


def play_game(command_list: List[str]) -> int:
    pos = acc = 0
    pos_seen = set([0])
    while pos < len(command_list):
        command = command_list[pos]
        pos_diff, acc_diff = get_state_diff(command, pos, acc)
        next_pos = pos + pos_diff
        if next_pos in pos_seen:
            raise Exception()
        else:
            pos_seen.add(next_pos)
            pos = next_pos
            acc += acc_diff
    return acc


if __name__ == "__main__":
    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, 'input.txt')
    command_list = parse_input(file_path)
    answer = calculate_answer(command_list)
    print(answer)
Пример #2
0
import os
from task1 import parse_input, build_input_dict, calculate_answer, TARGET_VALUE


def get_answer(in_dict: dict, target: int) -> dict:
    for k in in_dict.keys():
        remainder = target - k
        in_dict[k] -= 1
        solution = calculate_answer(in_dict, remainder)
        if solution is None:
            in_dict[k] += 1
        else:
            solution['c'] = k
            solution['mul'] *= k
            return solution
    return None


if __name__ == "__main__":
    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, 'input.txt')
    in_list = parse_input(file_path)
    in_dict = build_input_dict(in_list)
    answer = get_answer(in_dict, TARGET_VALUE)
    print(
        f'a: {answer["a"]}, b: {answer["b"]}, c: {answer["c"]}, mul: {answer["mul"]}'
    )
Пример #3
0
import os
from typing import Dict
from task1 import parse_input


def calculate_answer(bags: Dict[str, Dict[str, int]], color: str) -> int:
    return get_contained_bags(bags, color)


def get_contained_bags(bags: Dict[str, Dict[str, int]], color: str) -> int:
    bags_contained = 0
    for k, v in bags[color].items():
        bags_contained += v * (1 + get_contained_bags(bags, k))
    return bags_contained


if __name__ == "__main__":
    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, 'input.txt')
    bags = parse_input(file_path)
    answer = calculate_answer(bags, "shiny gold")
    print(answer)
Пример #4
0
        if i.startswith('mask'):
            mask = rh
        else:
            val = int(rh)
            addr = int(lh[4:-1])
            write_locations = get_address_list(mask, addr)
            for loc in write_locations:
                mem[loc] = val
    return sum([val for val in mem.values()])


def get_address_list(mask: str, addr: int) -> List[int]:
    # Prepare address
    prepared_addr = addr & int(mask.replace('0', '1').replace('X', '0'), 2)
    mask_list = get_mask_list(mask)
    return list(map(lambda m: m | prepared_addr, mask_list))


def get_mask_list(mask: str) -> List[int]:
    if 'X' not in mask:
        return [int(mask, 2)]
    return get_mask_list(mask.replace('X', '0', 1)) + get_mask_list(
        mask.replace('X', '1', 1))


if __name__ == '__main__':
    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, 'input.txt')
    instructions = parse_input(file_path)
    answer = calculate_answer(instructions)
    print(answer)
Пример #5
0
import os
from typing import List, Tuple
from task1 import parse_input, calculate_answer, Game

def check_in_direction(game_state: List[List[str]], row: int, col: int, direction: Tuple[int, int]) -> int:
    r_dir, c_dir = direction
    row_to_check = row + r_dir
    col_to_check = col + c_dir
    if row_to_check < 0 or row_to_check >= len(game_state):
        return 0
    if col_to_check < 0 or col_to_check >= len(game_state[row_to_check]):
        return 0
    if game_state[row_to_check][col_to_check] == game.TAKEN:
        return 1
    if game_state[row_to_check][col_to_check] == game.EMPTY:
        return 0
    return check_in_direction(game_state, row_to_check, col_to_check, direction)
    
if __name__ == "__main__":
    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, 'input.txt')
    game_map = parse_input(file_path)
    game = Game(check_in_direction, 5)
    answer = calculate_answer(game_map, game)
    print(answer)
Пример #6
0
                field_candidates[-1].append(name)
    return field_candidates


def remove_candidate(field_candidates: List[List[str]], c):
    for cand in field_candidates:
        try:
            cand.remove(c)
        except:
            pass


def discard_invalid_tickets(rules, tickets) -> List[List[int]]:
    validators = rules.values()
    valid_tickets = []
    for ticket in tickets:
        for val in ticket:
            validities = [f(val) for f in validators]
            if not any(validities):
                break
        else:
            valid_tickets.append(ticket)
    return valid_tickets


if __name__ == '__main__':
    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, 'input.txt')
    rules, tickets = parse_input(file_path)
    answer = calculate_answer(rules, tickets)
    print(answer)
Пример #7
0
from typing import List
from task1 import parse_input

class MagicNumber:
    def __init__(self, val):
        self.val = val

    def __add__(self, other):
        return MagicNumber(self.val * other.val)

    def __mul__(self, other):
        return MagicNumber(self.val + other.val)

def calculate_problem(problem: str) -> int:
    prepared_problem = problem
    for i in range(10):
        prepared_problem = prepared_problem.replace(str(i), f'MagicNumber({i})')
    prepared_problem = prepared_problem.replace('+', 'p').replace('*', '+').replace('p', '*')
    ret_val = {}
    exec(f'ret_val["res"]={prepared_problem}')
    return ret_val["res"].val

def calculate_answer(problems: List[str]) -> int:
    return sum([calculate_problem(p) for p in problems])

if __name__ == '__main__':
    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, 'input.txt')
    problems = parse_input(file_path)
    answer = calculate_answer(problems)
    print(answer)