Example #1
0
def parse_bag_rules():
    rules = utils.open_file('bag-rules.txt')

    bag_rules = {}

    for rule in rules:
        rule_parts = rule.split('contain')
        bag_key = rule_parts.pop(0).replace(' bags ', '')
        bags_contained = rule_parts.pop(0).split(',')

        this_bag = {}

        for bag in bags_contained:
            bag_parts = bag.strip('. ').split(' ', 1)
            bag_quantity = bag_parts[0]
            bag_color = bag_parts[1].replace(' bags', '').replace(' bag', '')

            this_bag[bag_color] = bag_quantity

        bag_rules[bag_key] = this_bag

    return bag_rules
Example #2
0
set_w_frequencies = set()
counter = 0


def count(numbers_list):
    global counter
    for i in numbers_list:
        try:
            counter += int(i)
            check_if_frequency_exist(counter)
        except ValueError:
            pass
    print("Sum:", counter)


def check_if_frequency_exist(frequency):
    global set_w_frequencies
    if frequency in set_w_frequencies:
        print("First duplicate:", frequency)
        sys.exit(0)
    else:
        set_w_frequencies.add(counter)


if __name__ == "__main__":
    numbers = open_file("utils/Day1_list.txt")
    l_numbers = string_to_list(numbers)
    while True:
        count(l_numbers)
Example #3
0
import utils.utils as utils

answers = utils.open_file('answers.txt')

# PART ONE #
already_answered = []
questions_count = 0

for answer in answers:
    if not answer:
        questions_count += len(already_answered)
        already_answered = []
        continue

    for question in answer:
        if question not in already_answered:
            already_answered.append(question)

print(questions_count)

# PART TWO #
questions_count = 0
people_in_group_count = 0
questions_answered = {}

for answer in answers:
    if not answer:
        for question_answered in questions_answered:
            if questions_answered[question_answered] == people_in_group_count:
                questions_count += 1
        people_in_group_count = 0
Example #4
0
        for number in range(width_of_codes):
            # TODO: Hoppa över det egna id:t (the_id)
            if list_any_id[number] == list_the_id[number]:
                counter += 1
            else:
                pass
        if counter == (width_of_codes - 1):
            find_shared_letters(list_the_id, list_any_id)


# todo: byt namn så det blir tydligare vad funktionen gör
def find_shared_letters(id_one, id_two):
    letters = []
    for number in range(len(id_one)):
        if id_one[number] == id_two[number]:
            letters.append(id_one[number])
        else:
            pass
    print("".join(letters))
    # todo: lägg detta i main. Returnera hellre ett värde.
    sys.exit(0)


if __name__ == "__main__":
    ids = open_file("utils/Day2_list.txt")
    id_list = string_to_list(ids)
    count_letters(id_list)
    print("Twos:", twos, "Threes:", threes, "Checksum:", twos * threes)
    for x in id_list:
        find_correct_boxes(x, id_list)
Example #5
0
                                                    waypoint_east)
    if instruction == 'L':
        rotations = (value % 360) / 90
        [waypoint_north,
         waypoint_east] = resolve_waypoint_rotation(rotations, waypoint_north,
                                                    waypoint_east)

    return process_instruction_with_waypoint(instructions, north, east,
                                             waypoint_north, waypoint_east)


def resolve_waypoint_rotation(rotations, waypoint_north, waypoint_east):
    rotations_made = 0
    while rotations_made < rotations:
        waypoint_east_aux = waypoint_east
        waypoint_east = -waypoint_north
        waypoint_north = waypoint_east_aux
        rotations_made += 1

    return [waypoint_north, waypoint_east]


instructions = utils.open_file('instructions.txt')

[north, east] = process_instruction_with_waypoint(instructions, 0, 0, 1, 10)

print('north ', north)
print('east ', east)

print(abs(north) + abs(east))
Example #6
0
def main():

    # load puz file
    fname = open_file()
    puz_name = os.path.basename(fname)[:-4]
    if os.path.realpath(
            fname[:-(len(puz_name) + 4)]) != os.path.realpath(PUZ_DIR):
        # save copy of puzzle in puzzle directory
        with open(fname, 'rb') as fr:
            with open(PUZ_DIR + puz_name + '.puz', 'wb') as fw:
                shutil.copyfileobj(fr, fw)
    p = puz.read(fname)

    # ask user whether generate (partial) solution
    get_sol = yesno_dialog("Find Solution?",
                           "Do you want to automatically find the solution?")
    if get_sol and any([c not in ['.', '-'] for c in p.fill]):
        get_sol = yesno_dialog(
            "Find Solution?",
            "Puzzle is not empty, finding solution will overwrite puzzle data.  Proceed anyway?"
        )

    if get_sol:
        # make sure p is empty
        p.fill = [c if c in ['.', '-'] else '-' for c in p.fill]

        # ask user to choose clue model and solver
        d1 = dialogbox("Clue model?",
                       "Which clue model do you want to use?",
                       o1='Oracle',
                       o2='Web')
        d2 = dialogbox("Solver?",
                       "Which solver do you want to use?",
                       o1='Backtracking',
                       o2='Priority Search')
        clue_solver = ["oracle", "web"][d1]
        solver = [
            BacktrackSolver(clue_model_type=clue_solver, puz_name=puz_name),
            PrioritySolver(clue_model_type=clue_solver, puz_name=puz_name)
        ][d2]

        sol, clue_model = solver.solve_puz(p)
        print("\nsolution:")
        board = sol.grid
        candidates = clue_model.candidates
    else:
        board, candidates = None, None

    # initialize board gui based on pygame
    pg.init()
    board_data = DisplayData(CLUE_HEIGHT=30,
                             COLOR_INACTIVE=pg.Color('white'),
                             COLOR_ACTIVE=pg.Color('yellow'),
                             COLOR_TEXT=pg.Color('black'),
                             COLOR_BORDER=pg.Color('black'),
                             COLOR_SELECT=pg.Color('red'),
                             COLOR_CLUE_BG=pg.Color('gray'),
                             GRID_FONT=pg.font.Font(None, 50),
                             CLUE_FONT=pg.font.Font(None, 30),
                             CLUE_NUM_FONT=pg.font.Font(None, 16))
    screen = pg.display.set_mode((900, 900 + 2 * board_data.CLUE_HEIGHT))
    pg.display.set_caption('"' + p.title + '" ' + p.author)
    board = BoardGUI(screen,
                     p,
                     board=board,
                     candidates=candidates,
                     board_data=board_data)

    clock = pg.time.Clock()
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            board.handle_event(event)

        screen.fill(board_data.COLOR_BORDER)
        board.draw(screen)

        pg.display.flip()
        clock.tick(30)

    pg.quit()

    # ask if user wants to save puzzle
    save = yesno_dialog("Save?", "Do you want to save the puzzle?")

    if save:
        # TODO: make sure clue models return uppercase letters, then remove .upper here and elsewhere
        new_fill = ''.join(
            [''.join([l.upper() for l in row]) for row in board.board])
        p.fill = new_fill
        p.save(fname)
import utils.utils as utils


def calculate_required_fuel(mass):
    return (mass // 3) - 2


spacecraft_modules = utils.open_file('spacecraft-modules.txt')

# PART ONE #
total_fuel = 0

for module_mass in spacecraft_modules:
    total_fuel += calculate_required_fuel(int(module_mass))

print(total_fuel)


# PART TWO #
def calculate_required_fuel_for_fuel(fuel_mass):
    required_fuel = calculate_required_fuel(fuel_mass)

    if required_fuel < 0:
        return 0

    return required_fuel + calculate_required_fuel_for_fuel(required_fuel)


total_fuel = 0

for module_mass in spacecraft_modules:
Example #8
0
        for h_point in horiz_list:
            for v_point in vert_list:
                self.claimed_inches.append((h_point, v_point))

"""
def check_if_claim_is_uique():
    pass
"""

def register_claimed_inches(obj):
    for square_inch in obj.claimed_inches:
        if square_inch not in claimed_inch:
            claimed_inch.add(square_inch)
        else:
            double_claimed_inch.add(square_inch)


"""def find_unique_claim():
    print(len(all_claim_ids))
    print(len(all_double_claiming_claim_ids))
    #print(all_claim_ids.difference(all_double_claiming_claim_ids))
"""

if __name__ == "__main__":
    claim_data = open_file("utils/Day3_list.txt")
    claim_list = string_to_list(claim_data)
    for c in claim_list:
        claim_object = Claim(c)
        register_claimed_inches(claim_object)
    print(len(double_claimed_inch))
def get_number(chars, number_range, lower_half_id):
    if not chars:
        return number_range[0]

    char = chars.pop(0)
    middle = (number_range[0] + number_range[1]) // 2

    if char == lower_half_id:
        return get_number(chars, [number_range[0], middle], lower_half_id)

    return get_number(chars, [middle + 1, number_range[1]], lower_half_id)


# PART ONE #
boarding_passes = utils.open_file('boarding-passes.txt')

seat_ids = []

for boarding_pass in boarding_passes:
    row = get_number(list(boarding_pass[0:7:]), [0, 127], 'F')
    column = get_number(list(boarding_pass[7::]), [0, 7], 'L')
    seat_id = row * 8 + column
    seat_ids.append(seat_id)

seat_ids.sort()
print(seat_ids[len(seat_ids) - 1])

# PART TWO #
for i in range(1, len(seat_ids)):
    id_minus_1 = seat_ids[i - 1]