Пример #1
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    logging.info('Started')
    lv = LoadValues()
    numbers = lv.list_to_intlist()
    logging.debug(len(numbers))
    preamble = 25

    for i in range(len(numbers) - preamble - 1):
        number = numbers[i + preamble]
        candidates = numbers[i:i + preamble]
        res = is_sum(number, candidates)
        if not res:
            break
    print("Star 1 : ", number)

    (start, end) = find_contiguous(number, numbers)
    logging.debug((start, end))
    logging.debug(numbers[start:end])
    min_val = min(numbers[start:end])
    max_val = max(numbers[start:end])

    print("Star 2 : ", min_val + max_val)

    logging.info('Finished')
Пример #2
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    logging.info('Started')
    lv = LoadValues()
    lv.strip_lines()

    idlist = [find_seat(boardingpass) for boardingpass in lv.processed_values]
    maxid = max(idlist)
    print("Star1 :", maxid)

    idlist.sort()
    minid = min(idlist)
    missing_values = []

    for idvalue in range(minid, maxid):
        if idvalue not in idlist:
            missing_values.append(idvalue)
    print("Star2 :", missing_values)

    idlist = [
        convert_string_to_seatid(boardingpass)
        for boardingpass in lv.processed_values
    ]
    maxid = max(idlist)
    print("Star1bis :", maxid)
    minid = min(idlist)
    missing_values = []

    for idvalue in range(minid, maxid):
        if idvalue not in idlist:
            missing_values.append(idvalue)
    print("Star2bis :", missing_values)

    logging.info('Finished')
Пример #3
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    logging.info('Started')
    lv = LoadValues()
    lines = lv.strip_lines()

    instr = get_instructions(lines)
    prog = Program(instr)
    (_, ip, acc) = prog.does_terminate()
    print("Star 1 : ", acc)

    finished = None
    for (i, cur_instr) in enumerate(instr):
        if cur_instr[0] == 'nop' or cur_instr[0] == 'jmp':
            instr2 = instr.copy()
            if cur_instr[0] == 'nop':
                instr2[i] = ('jmp', cur_instr[1])
            else:
                instr2[i] = ('nop', cur_instr[1])
            (res, ip, acc) = Program(instr2).does_terminate()
            if res:
                finished = (ip, acc)
                break

    print("Star 2 : ", acc)

    logging.info('Finished')
Пример #4
0
def main():
    lv = LoadValues()
    seat_list = lv.strip_lines()
    logging.debug(seat_list)
    pr.enable()
    seats = SeatPlan(seat_list)
    logging.debug(seats.seats)

    cur_seat = seats.people
    new_seat = []
    while cur_seat != new_seat:
        cur_seat = new_seat
        new_seat = seats.new_seating()

    logging.debug("OK")
    number = sum([sum(line) for line in cur_seat])
    print("Star 1 : ", number)
    seats = SeatPlan(seat_list)

    seats = SeatPlan(seat_list)
    logging.debug(seats.seats)

    cur_seat = seats.people
    new_seat = []
    while cur_seat != new_seat:
        cur_seat = new_seat
        new_seat = seats.new_seating_line()
        print("\n".join(seats.array_seat()))
    number = sum([sum(line) for line in cur_seat])

    print("Star 2 : ", number)
    pr.disable()
    logging.info('Finished')
Пример #5
0
def main():
    lv = LoadValues()
    lines = lv.strip_lines()

    earlier = int(lines[0])
    times = lines[1].split(',')
    logging.debug((earlier, times))
    best_time = earlier * 2
    bus_times = [(i, int(val)) for (i, val) in enumerate(times) if val != 'x']
    logging.debug(bus_times)

    bus = 0
    for (offset, t) in bus_times:
        first = (earlier // t + 1) * t
        logging.debug((earlier, t, first))
        if first < best_time:
            bus = t
            best_time = first
    logging.debug((bus, best_time))
    number = bus * (best_time - earlier)
    print("Star 1 : ", number)

    bus_period = [period for (offset, period) in bus_times]
    bus_offset = [(period - offset) % period for (offset, period) in bus_times]
    logging.debug(bus_period)
    logging.debug(bus_offset)

    number = chinese_remainder(bus_period, bus_offset)
    print("Star 2 : ", number)
    logging.info('Finished')
Пример #6
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    logging.info('Started')
    lv = LoadValues("test.txt")
    lines = lv.strip_lines()
    graph = build_graph(lines)
    print(graph)
    cnt = count_ascendants(('shiny', 'gold'), graph[0])
    print("Star 1 : ", len(set(cnt)))
    cnt = count_descendants(('shiny', 'gold'), graph[1])
    print("Star 2 : ", cnt - 1)

    logging.info('Finished')
Пример #7
0
    def setUp(self):
        lv = LoadValues("test.txt", groups=True)

        self.tiles = {}
        for tile in lv.raw_values:
            cur_tile = Tile(tile)
            self.tiles[cur_tile.tileId] = cur_tile
Пример #8
0
def main():
    number = 0

    lv = LoadValues("input.txt", groups=True)

    rules, messages = lv.raw_values

    RS = RuleSet()
    RS.build_rules(rules)
    logging.debug(RS.rules)

    res = [(len(m), RS.build_valid(m, 0)) for m in messages]
    logging.debug(res)
    match = [mlen in mset for (mlen, mset) in res]
    number = sum(match)

    print("Star 1 : ", number)

    rules.append("8: 42 | 42 8")
    rules.append("11: 42 31 | 42 11 31")

    RS = RuleSet()
    RS.build_rules(rules)
    logging.debug(RS.rules)

    res = [(len(m), RS.build_valid(m, 0)) for m in messages]
    logging.debug(res)
    match = [mlen in mset for (mlen, mset) in res]
    number = sum(match)

    print("Star 2 : ", number)
Пример #9
0
def main():
    number = 0

    lv = LoadValues()
    lines = lv.strip_lines()

    start = [0, 3, 6]
    start = [3, 1, 2]
    # start = [1, 0, 18, 10, 19, 6]  # Real Input
    number = numbers_sequence(start, 2020)

    print("Star 1 : ", number)

    number = numbers_sequence(start, 30000000)

    print("Star 2 : ", number)
    logging.info('Finished')
Пример #10
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    logging.info('Started')
    lv = LoadValues()
    lv.strip_lines()
    passports = (lv.passportlist_parse())

    cntstar1 = 0
    cntstar2 = 0

    for passportfields in passports:
        passport = Passport()
        passport.set_fields(passportfields)
        if passport.are_compulsory_keys_present():
            cntstar1 += 1
        if passport.isvalid_passport():
            cntstar2 += 1

    print(cntstar1, cntstar2)
    logging.info('Finished')
Пример #11
0
def main():
    lv = LoadValues()
    action_list = [(line[0], line[1:]) for line in lv.strip_lines()]
    logging.debug(action_list)
    ship = Ship()
    for action in action_list:
        pass
        ship.act(action)
    (x, y) = ship.pos
    number = abs(x) + abs(y)

    print("Star 1 : ", number)

    ship = ShipW()
    for action in action_list:
        ship.act(action)
    (x, y) = ship.pos
    number = abs(x) + abs(y)

    print("Star 2 : ", number)
    logging.info('Finished')
Пример #12
0
def main():
    lv = LoadValues()
    numbers = lv.list_to_intlist()
    logging.debug(len(numbers))
    adapters = [0] + numbers + [max(numbers) + 3]
    logging.debug(adapters)

    adapters.sort()
    logging.debug(adapters)
    diff = [adapters[i + 1] - adapters[i] for i in range(len(adapters) - 1)]
    logging.debug(diff)

    one = sum([i == 1 for i in diff])
    three = sum([i == 3 for i in diff])
    logging.debug((one, three, one * three))
    print("Star 1 : ", one * three)

    pr.enable()
    number = count_paths_list(0, len(adapters) - 1, adapters)
    print("Star 2 : ", number)
    pr.disable()
    logging.info('Finished')
Пример #13
0
def main():
    number = 0

    lv = LoadValues()
    lines = lv.strip_lines()

    # lines = ["1 + 2 * 3 + 4 * 5 + 6", "1 + ( 2 * 3 ) + ( 4 * ( 5 + 6 ) )","((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2"]

    # expr = expr.replace('(', '( ')
    # expr = expr.replace(')', ' )')
    # ops = expr.split()
    # r1 = shunting(ops)
    # logging.debug(("r1:", r1))
    # r2 = eval_rpn(r1)
    # logging.debug(("r2:", r2))

    (acc1, acc2) = (0, 0)
    for line in lines:
        expr = line
        expr = expr.replace('(', '( ')
        expr = expr.replace(')', ' )')
        ops = expr.split()
        r1 = shunting(ops)
        r2 = eval_rpn(r1)
        logging.debug(("r1:", r1))
        logging.debug(("r2:", r2))
        acc1 += r2
        ops = expr.split()
        r1 = shunting(ops, advanced=True)
        r2 = eval_rpn(r1)
        acc2 += r2

    number = acc1

    print("Star 1 : ", number)
    number = acc2

    print("Star 2 : ", number)
    logging.info('Finished')
Пример #14
0
def main():
    number = 0

    lv = LoadValues()
    grid = lv.strip_lines()
    myPD = PocketDim()
    myPD.fill_pocket_dim(grid)

    logging.debug(myPD.active)
    myP = Coord((1, 1, 1))

    # logging.debug(myP.get_neigh())

    for i in range(6):
        myPD = myPD.step()
        logging.debug((len(myPD.active), myPD.active))

    number = len(myPD.active)
    print("Star 1 : ", number)

    print("Star 2 : ", number)
    logging.info('Finished')
Пример #15
0
def main():
    number = 0

    lv = LoadValues(groups=True)

    tv = TicketValidator()
    tv.set_fields(lv.raw_values[0])
    ticket_list = lv.raw_values[2][1:]
    my_ticket = [int(val) for val in str(lv.raw_values[1][1:][0]).split(',')]
    logging.debug(ticket_list)
    valid_tickets = []
    for ticket in ticket_list:
        values = [int(i) for i in ticket.split(',')]
        logging.debug(("values :", values))
        (isValid, tmp) = tv.is_ticket_valid(values)
        number += tmp
        if isValid:
            valid_tickets.append(values)

    print("Star 1 : ", number)

    nb_fields = len(valid_tickets[0])
    field_val = 0

    valid_fields = [set(tv.fields.keys()) for i in range(nb_fields)]

    for ticket in valid_tickets:
        for (i, val) in enumerate(ticket):
            res = set(tv.get_valid_fields_for_value(val))
            valid_fields[i] = valid_fields[i].intersection(res)
    known_fields_val = {}
    known_fields_set = set()
    valid_fields = [(pos, valid) for (pos, valid) in enumerate(valid_fields)]
    valid_fields.sort(key=lambda val: len(val[1]), reverse=True)
    while len(valid_fields) > 0:
        cur_field = valid_fields.pop()
        (col, possible) = cur_field
        res = possible.difference(known_fields_set)
        res = res.pop()
        known_fields_val[res] = col
        known_fields_set.add(res)

    # calculate 2nd star
    number = 1
    for k in known_fields_val:
        if k[:9] == 'departure':
            number *= my_ticket[known_fields_val[k]]
    print("Star 2 : ", number)
    logging.info('Finished')
Пример #16
0
def main():
    logging.basicConfig(level=logging.INFO)
    logging.info('Started')
    lv = LoadValues(groups=True)

    groups = [line for line in lv.raw_values]
    logging.debug(groups)
    res = [(list_questions_for_group_union(group)) for group in groups]
    cnt = sum(res)
    print("Star 1 : ", cnt)
    res = [(list_questions_for_group_intersection(group)) for group in groups]
    cnt = sum(res)
    print("Star 2 : ", cnt)

    logging.info('Finished')
Пример #17
0
def main():
    pr = cProfile.Profile()

    logging.basicConfig(level=logging.DEBUG)
    graph_logger_maze.setLevel(logging.INFO)
    logging.info('Started')
    pr.enable()

    lv = LoadValues()
    lv.strip_lines()
    my_maze = Maze()
    my_maze.build_maze(lv.processed_values)
    nodes = my_maze.get_graph()
    my_graph = Graph(my_maze)
    # print(my_graph.graph[(0,0)])
    # print(my_graph.get_cell((0,1)))
    print("_____________________")
    distances = my_graph.bfs((0, 0))
    dist_list = distances.items()
    print(sorted(dist_list, key=lambda dist: dist[1]))
    pr.disable()

    logging.info('Finished')
    pr.print_stats()
Пример #18
0
def main():
    number = 0

    lv = LoadValues("input.txt")
    lines = lv.strip_lines()

    print(lines[0])
    dirs = (parse_directions(lines[0]))
    c = pointer()
    for dir in dirs:
        c.move(dir)
        print(dir, c)

    tiles = {}
    for line in lines:
        dirs = parse_directions(line)
        c = pointer()
        for dir in dirs:
            c.move(dir)
        if c.pos in tiles:
            tiles.pop(c.pos)
        else:
            tiles[c.pos] = c
    print(tiles)
    number = len(tiles)

    print("Star 1 : ", number)

    new_pos = tiles.keys()
    for i in range(100):
        new_pos = game(new_pos)
        print(i + 1, len(new_pos))

    number = len(new_pos)

    print("Star 2 : ", number)
Пример #19
0
def main():
    lv = LoadValues()
    lines = lv.strip_lines()

    mem = Memory()

    for line in lines:
        logging.debug(line)
        args = line.split(' = ')
        if args[0] == 'mask':
            mem.set_mask(args[1])
        else:
            logging.debug(("addr", args[0][4:-1]))
            mem_addr = int(args[0][4:-1])
            mem.set_mem(mem_addr, int(args[1]))

    number = mem.get_mem()

    print("Star 1 : ", number)

    mem = MemoryV2()

    for line in lines:
        logging.debug(line)
        args = line.split(' = ')
        logging.debug(args)
        if args[0] == 'mask':
            mem.set_mask(args[1])
        else:
            logging.debug(("addr", args[0][4:-1]))
            mem_addr = int(args[0][4:-1])
            mem.set_mem(mem_addr, int(args[1]))
    number = mem.get_mem()

    print("Star 2 : ", number)
    logging.info('Finished')
Пример #20
0
def main():
    number = 0

    lv = LoadValues("input.txt", groups=True)

    decks = []
    for lines in lv.raw_values:
        (player, deck) = parse_deck(lines)
        decks.append(deck)

    print(decks)
    gc = GameCounter()

    winddeck = do_game(decks[0].copy(), decks[1].copy())
    number = score_deck(winddeck)
    print("Star 1 : ", number)

    print(score_deck(deque([7, 5, 6, 2, 4, 1, 10, 8, 9, 3])))
    deck1, deck2 = decks[0].copy(), decks[1].copy()
    winner, winddeck = recursive_game(deck1, deck2, gc)
    number = score_deck(winddeck)
    print("Star 2 : ", number)
Пример #21
0
def main():
    number = 0

    lv = LoadValues("input.txt")
    lines = lv.strip_lines()
    possib_aller = dict()
    all_ingredients = set()
    for line in lines:
        (ingredients, allergens) = parse_recipe(line)
        all_ingredients |= set(ingredients)
        for aller in allergens:
            if aller in possib_aller:
                possib_aller[aller] &= set(ingredients)
            else:
                possib_aller[aller] = set(ingredients)

    logging.debug(possib_aller)
    remove_ingr = set()
    for (aller, ingr) in possib_aller.items():
        remove_ingr |= ingr

    no_aller = all_ingredients - remove_ingr
    logging.debug(no_aller)  # ingredients that cannot contain allergens

    cnt = 0
    for line in lines:
        (ingredients, allergens) = parse_recipe(line)
        cnt += len(set(ingredients) & no_aller)

    number = cnt
    print("Star 1 : ", number)

    candidate_aller = possib_aller.copy()
    to_remove = []
    found = []
    for (aller, ingr) in candidate_aller.copy().items():
        if len(ingr) == 1:
            val = ingr.pop()
            to_remove.append(val)
            found.append((aller, val))
            candidate_aller.pop(aller)

    while to_remove:
        cur_ingr = to_remove.pop()
        logging.debug(cur_ingr)
        for (aller, ingr) in candidate_aller.copy().items():
            ingr.discard(cur_ingr)
            if len(ingr) == 1:
                val = ingr.pop()
                to_remove.append(val)
                found.append((aller, val))
                candidate_aller.pop(aller)
        logging.debug("-------")
        logging.debug(candidate_aller)
        logging.debug(to_remove)
        logging.debug(found)
        logging.debug("-------")

    found.sort()  # sort by allergen
    logging.debug(found)
    number = ','.join([ingr for (aller, ingr) in found])

    print("Star 2 : ", number)
Пример #22
0
from loadValues import LoadValues

lv = LoadValues().strip_lines()

height = len(lv)
width = len(lv[0])

print(height, width, lv)


def convertw(y):
    (div, mod) = divmod(y, width)
    return mod


def trees_for_slope(slopex, slopey):
    (posx, posy) = (0, 0)
    cnt = 0
    while (posx < height - 1):
        posx += slopex
        posy += slopey
        # print(posx, posy, convertw(posy))
        if (lv[posx][convertw(posy)] == "#"):
            cnt += 1
    return (cnt)


slope = trees_for_slope(1, 3)
print("1 star : ", slope)

slope1 = trees_for_slope(1, 1)
Пример #23
0
 def setUp(self):
     lv = LoadValues("test.txt", groups=True)
     self.tl = TileList()
     for tile in lv.raw_values:
         T = Tile(tile)
         self.tl.add_tile(T)
Пример #24
0
from loadValues import LoadValues

lv = LoadValues()
database = lv.get_rules()


def check_rule_1star(rule, password):
    (letter, (qmin, qmax)) = rule
    counter = password.count(letter)
    if counter >= qmin and counter <= qmax:
        return True
    else:
        return False


def check_rule_2star(rule, password):
    (letter, (pos1, pos2)) = rule
    res1 = password[pos1 - 1] == letter
    res2 = password[pos2 - 1] == letter
    return res1 ^ res2


(cnt1, cnt2) = (0, 0)
for (rule, password) in database:
    res1 = check_rule_1star(rule, password)
    res2 = check_rule_2star(rule, password)
    if res1:
        cnt1 += 1
    if res2:
        cnt2 += 1
    print(rule, password, (res1, res2))