示例#1
0
 def runModelTestMultiple(self, budget, function, instance, dimension,
                          esconfig, checkPoint, logger, pflacco,
                          localSearch, models, stepSize, precision):
     problem = Problem(budget,
                       function,
                       instance,
                       dimension,
                       esconfig,
                       checkPoint,
                       logger,
                       pflacco,
                       localSearch,
                       precision=precision)
     problem.runTestMultipleModels(models, stepSize)
示例#2
0
def load(p: Problem):
    foods = []
    for food in p.data():
        ingredients = food.split(' (')[0].split()
        allergens = food.split(' (')[1].replace('contains ',
                                                '').rstrip(')').split(', ')
        foods.append((ingredients, allergens))
    return foods
示例#3
0
def load(p: Problem):
    data = p.raw_data().split('\n\n')
    rules = {}
    for line in data[0].split('\n'):
        match = RULE_PATTERN.match(line)
        rules[int(match.group(1))] = match.group(4) if match.group(4) else [[
            int(r) for r in opt.split(' ')
        ] for opt in match.groups()[1:] if opt]
    return {"rules": rules, "messages": data[1].split('\n')}
示例#4
0
def load(p: Problem):
    return p.data(dtype=int)
示例#5
0
    # Diagonal up-left
    for r, c in zip(reversed(range(0, r0)), reversed(range(0, c0))):
        if seats[r][c] == OCCUPIED:
            n += 1
            break
        if seats[r][c] == FREE:
            break
    # Diagonal down-left
    for r, c in zip(range(r0 + 1, len(seats)), reversed(range(0, c0))):
        if seats[r][c] == OCCUPIED:
            n += 1
            break
        if seats[r][c] == FREE:
            break
    # Diagonal up-right
    for r, c in zip(reversed(range(0, r0)), range(c0 + 1, len(seats[0]))):
        if seats[r][c] == OCCUPIED:
            n += 1
            break
        if seats[r][c] == FREE:
            break
    return n


if __name__ == '__main__':
    problem = Problem(11)
    data = load()

    problem.submit(part_a(), 'a')  # 2243
    problem.submit(part_b(), 'b')  # 2027
示例#6
0
def load(p: Problem):
    return [re.findall(PATTERN, instr) for instr in p.data()]
示例#7
0
        return False, 0

    s, read = _parse(0, msg)
    return s and read == len(msg)


def patch_rules(data: dict, n_8: int, n_11: int):
    data["rules"][8] = [[42] + [42] * n_8]
    data["rules"][11] = [[42] + [42] * n_11 + [31] * n_11 + [31]]


def load(p: Problem):
    data = p.raw_data().split('\n\n')
    rules = {}
    for line in data[0].split('\n'):
        match = RULE_PATTERN.match(line)
        rules[int(match.group(1))] = match.group(4) if match.group(4) else [[
            int(r) for r in opt.split(' ')
        ] for opt in match.groups()[1:] if opt]
    return {"rules": rules, "messages": data[1].split('\n')}


if __name__ == '__main__':
    problem = Problem(19)

    print(part_a(load(problem)))
    print(part_b(load(problem)))

    #problem.submit(part_a(load(problem)), 'a')  # 156
    #problem.submit(part_b(load(problem)), 'b')  # 363
示例#8
0
def load(p: Problem):
    return sorted(
        p.data(dtype=int) +
        [0, max(p.data(dtype=int)) + 3])  # Append charging outlet and adapter
示例#9
0
def load(p: Problem):
    return p.raw_data()
示例#10
0

def part_b():
    return play(30_000_000)


def play(turns):
    memory = deepcopy(data)
    last_num = list(data.keys())[-1]
    for turn in range(len(data), turns):
        # Use double assignment to avoid temporarily saving the last_num for storing its turn
        memory[
            last_num], last_num = turn, 0 if last_num not in memory else turn - memory[
                last_num]
    return last_num


def load():
    return {
        int(num): turn
        for turn, num in enumerate(problem.data()[0].split(','), 1)
    }


if __name__ == '__main__':
    problem = Problem(15)
    data = load()

    problem.submit(part_a(), 'a')  # 1194
    problem.submit(part_b(), 'b')  # 48710
示例#11
0
    with open('entries.txt', 'w') as fh:
        for entry in entries.items():
            node, children = entry
            fh.write(f"{node}: {children}\n")


def pickle_trees():
    entries = parse_nodes(problem.data())
    trees = build_trees(entries)
    with open('trees.pkl', 'wb') as fh:
        pkl.dump(trees, fh)


def load():
    with open('trees.pkl', 'rb') as fh:
        return pkl.load(fh)


if __name__ == '__main__':
    problem = Problem(7)
    # pickle_trees()
    trees = load()

    # Collect every 'shiny gold bag' nodes in all trees
    shiny_gold_bags = list()
    for tree in trees:
        find_nodes('shiny gold bag', tree, shiny_gold_bags)

    problem.submit(part_a(), 'a')  # 124
    problem.submit(part_b(), 'b')  # 34862
示例#12
0
                  "W": lambda u, ship: ship.move_waypoint(Cardinal.WEST, u),
                  "L": lambda d, ship: ship.turn_waypoint(Direction.LEFT, d),
                  "R": lambda d, ship: ship.turn_waypoint(Direction.RIGHT, d),
                  "F": lambda u, ship: ship.forward_waypoint(u)}


def part_a():
    ship = Ship()
    for instr, param in data:
        INSTRUCTIONS_A[instr](param, ship)
    return abs(ship.position[0]) + abs(ship.position[1])


def part_b():
    ship = Ship()
    for instr, param in data:
        INSTRUCTIONS_B[instr](param, ship)
    return abs(ship.position[0]) + abs(ship.position[1])


def load():
    return [(i[0], int(i[1:])) for i in problem.data()]


if __name__ == '__main__':
    problem = Problem(12)
    data = load()

    problem.submit(part_a(), 'a')  # 1032
    problem.submit(part_b(), 'b')  # 156735
示例#13
0
            if all(rules[r](ticket.split(',')[pos]) for ticket in tickets):
                if unique_rule:  # If more then one rule applies to the position, skip the position
                    unique_rule = None
                    break
                unique_rule = (r, pos)
        # If unique rule was found, return it
        if unique_rule:
            return unique_rule


def load():
    data = problem.data()
    your_ticket = data.index('your ticket:')
    nearby_tickets = data.index('nearby tickets:')
    return [
        data[:your_ticket - 1], data[your_ticket + 1],
        data[nearby_tickets + 1:]
    ]


if __name__ == '__main__':
    problem = Problem(16)
    data = load()

    rules = {(m := RULE_PATTERN.match(line)).group(1):
             _rule_closure(m.group(2), m.group(3), m.group(4), m.group(5))
             for line in data[0]}

    problem.submit(part_a(), 'a')  # 20091
    problem.submit(part_b(), 'b')  # 2325343130651
示例#14
0
def part_a():
    return sum([
        len(answer) for answer in [
            set([answer for person in group.split('\n') for answer in person])
            for group in data
        ]
    ])


def part_b():
    return sum([
        len(answer) for answer in [
            set.intersection(*[
                set(answer for answer in person)
                for person in group.split('\n')
            ]) for group in data
        ]
    ])


def load():
    return problem.data(delim='\n\n')


if __name__ == '__main__':
    problem = Problem(6)
    data = load()

    problem.submit(part_a(), 'a')  # 6625
    problem.submit(part_b(), 'b')  # 3360
示例#15
0
        occ = password.count(letter)
        if min_occ <= occ <= max_occ:
            valid_entries += 1

    return valid_entries


def part_b():
    valid_entries = 0
    for entry in data:
        pos1 = int(entry.split("-")[0]) - 1
        pos2 = int(entry.split("-")[1].split(" ")[0]) - 1
        letter = entry.split(" ")[1].split(":")[0]
        password = entry.split(" ")[2]
        if (password[pos1] == letter) ^ (password[pos2] == letter):
            valid_entries += 1

    return valid_entries


def load():
    return problem.data()


if __name__ == '__main__':
    problem = Problem(2)
    data = load()

    problem.submit(part_a(), 'a')  # 600
    problem.submit(part_b(), 'b')  # 245
                break
            if id == first_id:
                timestamp = nearest
        if matching == len(int_data_b) - 1:
            break
        i += 1
        if i % 1_000_000 == 0:
            print(timestamp)

    return timestamp


def nearest_timestamp(id: int, t0: int, offset: int):
    if offset < 0:
        return floor(t0 / id) * id
    elif offset > 0:
        return ceil(t0 / id) * id


def load():
    return [int(problem.data()[0])] + [b for b in problem.data()[1].split(',')]


if __name__ == '__main__':
    problem = Problem(13)
    data = load()
    bus_data = [int(d) for d in filter(lambda b: b != 'x', data)]

    # problem.submit(part_a(), 'a')
    # problem.submit(part_b(), 'b')
示例#17
0
from src.problem import Problem
import itertools


def part_a():
    comb = itertools.combinations(data, 2)
    comb = [(a, b) for a, b in comb if a + b == 2020]
    return comb[0][0] * comb[0][1]


def part_b():
    comb = itertools.combinations(data, 3)
    comb = [(a, b, c) for a, b, c in comb if a + b + c == 2020]
    return comb[0][0] * comb[0][1] * comb[0][2]


def load():
    return problem.data(dtype=int)


if __name__ == '__main__':
    problem = Problem(1)
    data = load()

    problem.submit(part_a(), 'a')  # 960075
    problem.submit(part_b(), 'b')  # 212900130
示例#18
0
    play(nxt, moves=100)
    return ''.join(lmap(str, traverse(nxt, start=1, steps=len(nxt) - 1)))


def part_b(nxt: dict):
    total_cups = 1_000_000
    first, last = list(nxt.keys())[0], list(nxt.keys())[-1]

    # link new cups
    nxt[last], nxt[total_cups] = len(nxt) + 1, first
    for i in range(len(nxt), total_cups):
        nxt[i] = i + 1

    play(nxt, moves=10_000_000)
    return prod(traverse(nxt, start=1, steps=2))


def load(p: Problem):
    data = lmap(int, p.raw_data())
    return dict(zip(data, np.roll(data, -1)))


if __name__ == '__main__':
    problem = Problem(23)

    # print(part_a(load(problem)))  # 26354798
    # print(part_b(load(problem)))  # 166298218695

    # problem.submit(part_a(load(problem)), 'a')
    # problem.submit(part_b(load(problem)), 'b')
示例#19
0
def part_a():
    pocket_dim = np.expand_dims(data, axis=0)
    for _ in range(6):
        pocket_dim = convolve_cubes(pocket_dim, KERNEL_3D)
    return np.count_nonzero(pocket_dim == 1)


def part_b():
    pocket_dim = np.expand_dims(np.expand_dims(data, axis=0), axis=0)
    for _ in range(6):
        pocket_dim = convolve_cubes(pocket_dim, KERNEL_4D)
    return np.count_nonzero(pocket_dim == 1)


def convolve_cubes(grid: np.ndarray, kernel: np.ndarray):
    c = convolve(grid, kernel)
    return np.vectorize(lambda elem: elem in [3, 102, 103])(c)


def load():
    return np.array([list(line) for line in problem.data()]) == '#'


if __name__ == '__main__':
    problem = Problem(17)
    data = load()

    problem.submit(part_a(), 'a')  # 295
    problem.submit(part_b(), 'b')  # 1972
示例#20
0
def load(p: Problem):
    data = lmap(int, p.raw_data())
    return dict(zip(data, np.roll(data, -1)))
示例#21
0
    diffs = list(map(lambda x1, x2: x2 - x1, data, data[1:]))
    return diffs.count(1) * diffs.count(3)


def part_b(data: list):
    arr = [0] * len(data)
    for i in reversed(range(0, len(data) - 3)):
        arr[i] = arr[i + 1]
        for skip in (2,
                     3):  # can possible only skip next or the next next item
            if data[i + skip] - data[i] <= 3:
                arr[i] += arr[i + skip] + 1

    return arr[0] + 1  # add the initial arrangement


def load(p: Problem):
    return sorted(
        p.data(dtype=int) +
        [0, max(p.data(dtype=int)) + 3])  # Append charging outlet and adapter


if __name__ == '__main__':
    problem = Problem(10, test=False)

    # print(part_a(load(problem)))
    # print(part_b(load(problem)))

    # problem.submit(part_a(load(problem)), 'a')
    # problem.submit(part_b(load(problem)), 'b')
示例#22
0
            _play_move(p1_cards,
                       p2_cards) if p1_cards[0] > p2_cards[0] else _play_move(
                           p2_cards, p1_cards)

    return PLAYER_1 if len(p2_cards) == 0 else PLAYER_2


def _play_move(winner_cards: list[int], loser_cards: list[int]) -> None:
    winner_cards.append(winner_cards.pop(0))
    winner_cards.append(loser_cards.pop(0))


def _calculate_score(cards: list[int]) -> int:
    return sum(idx * card for idx, card in enumerate(reversed(cards), 1))


def load(p: Problem):
    data = p.raw_data().split('\n\n')
    return [[int(d) for d in data[0].split('\n')[1:]],
            [int(d) for d in data[1].split('\n')[1:]]]


if __name__ == '__main__':
    problem = Problem(22)

    # print(part_a(load(problem)))
    print(part_b(load(problem)))

    # problem.submit(part_a(load(problem)), 'a')
    # problem.submit(part_b(load(problem)), 'b')
示例#23
0
            ingredient = set.intersection(*containing)

            if len(ingredient) == 1:
                ingredient = ingredient.pop()
                allergen_map[ingredient] = allergen
                for food in foods:
                    if ingredient in food[0]:
                        food[0].remove(ingredient)
        allergens.difference_update(allergen_map.values())
    return allergen_map


def load(p: Problem):
    foods = []
    for food in p.data():
        ingredients = food.split(' (')[0].split()
        allergens = food.split(' (')[1].replace('contains ',
                                                '').rstrip(')').split(', ')
        foods.append((ingredients, allergens))
    return foods


if __name__ == '__main__':
    problem = Problem(21, test=False)

    # print(part_a(load(problem)))
    # print(part_b(load(problem)))

    # problem.submit(part_a(load(problem)), 'a')
    # problem.submit(part_b(load(problem)), 'b')
示例#24
0
def load(p: Problem):
    data = p.raw_data().split('\n\n')
    return [[int(d) for d in data[0].split('\n')[1:]],
            [int(d) for d in data[1].split('\n')[1:]]]
示例#25
0
    def adj(self, ref: Tile) -> list:
        return [tile for tile in self.tiles.values() if tile.is_adj(*ref.pos)]


def part_a(instructions: list):
    hexgrid = HexGrid()
    hexgrid.find_and_flip(instructions)
    return hexgrid.count_color(BLACK)


def part_b(instructions: list):
    hexgrid = HexGrid()
    hexgrid.find_and_flip(instructions)
    print(hexgrid.count_color(BLACK))
    hexgrid.live(iterations=100)
    return hexgrid.count_color(BLACK)


def load(p: Problem):
    return [re.findall(PATTERN, instr) for instr in p.data()]


if __name__ == '__main__':
    problem = Problem(24, test=False)

    # print(part_a(load(problem)))
    # print(part_b(load(problem)))

    # problem.submit(part_a(load(problem)), 'a')
    problem.submit(part_b(load(problem)), 'b')
示例#26
0
            term = self._expr()
            self._check(Token.Kind.rpar)
        else:
            raise RuntimeError("Term must be called with number or lpar token")
        return term


def part_a(data: str):
    parser = LRParser(data)
    for _ in range(len(data.split('\n'))):
        parser.parse()
    return sum(parser.results)


def part_b(data: str):
    parser = PunstriParser(data)
    for _ in range(len(data.split('\n'))):
        parser.parse()
    return sum(parser.results)


def load(p: Problem):
    return p.raw_data()


if __name__ == '__main__':
    problem = Problem(18)

    problem.submit(part_a(load(problem)), 'a')  # 8929569623593
    problem.submit(part_b(load(problem)), 'b')  # 231235959382961
示例#27
0
    def replace_at_index(s: str, r: str, idx: int) -> str:
        return s[:idx] + r + s[idx + 1:]


def part_a():
    decoder = Decoder()
    for cmd, args in data:
        decoder.interpret(cmd, args)
    return decoder.calc_sum()


def part_b():
    decoder = QuantumDecoder()
    for cmd, args in data:
        decoder.interpret(cmd, args)
    return decoder.calc_sum()


def load():
    return [(match.group(1), match.groups()[1:])
            for line in problem.data()
            for match in [p.match(line) for p in PATTERNS] if match]


if __name__ == '__main__':
    problem = Problem(14)
    data = load()

    problem.submit(part_a(), 'a')  # 6513443633260
    problem.submit(part_b(), 'b')  # 3442819875191
示例#28
0

def part_a():
    for i, num in enumerate(data[26:]):
        preamble = data[i:26 + i]
        if num not in [sum(pair) for pair in it.combinations(preamble, 2)]:
            return num


def part_b():
    for start, _ in enumerate(data):
        for end, acc in enumerate(it.accumulate(data[start:]), start):
            if acc == invalid_num:
                return min(data[start:end]) + max(data[start:end])
            if acc > invalid_num:
                break


def load():
    return problem.data(dtype=int)


if __name__ == '__main__':
    problem = Problem(9)
    data = load()

    invalid_num = part_a()

    problem.submit(invalid_num, 'a')  # 85848519
    problem.submit(part_b(), 'b')  # 13414198
示例#29
0
        if line[c[0]] == '#':
            n_trees[0] += 1
        c[0] = (c[0] + 1) % len(line)
        if line[c[1]] == '#':
            n_trees[1] += 1
        c[1] = (c[1] + 3) % len(line)
        if line[c[2]] == '#':
            n_trees[2] += 1
        c[2] = (c[2] + 5) % len(line)
        if line[c[3]] == '#':
            n_trees[3] += 1
        c[3] = (c[3] + 7) % len(line)
        if r % 2 == 0:
            if line[c[4]] == '#':
                n_trees[4] += 1
            c[4] = (c[4] + 1) % len(line)

    return n_trees[0] * n_trees[1] * n_trees[2] * n_trees[3] * n_trees[4]


def load():
    return problem.data()


if __name__ == '__main__':
    problem = Problem(3)
    data = load()

    problem.submit(part_a(), 'a')  # 292
    problem.submit(part_b(), 'b')  # 9354744432
示例#30
0
def transform(x: int, subj: int):
    return (x * subj) % 20201227


def part_a(pub_card: int, pub_door: int):
    x, loop = 1, 1
    while True:
        x = transform(x, subj=7)
        if x in (pub_card, pub_door):
            break
        loop += 1

    subject = pub_card if x == pub_door else pub_card
    x = 1
    for _ in range(loop):
        x = transform(x, subject)

    return x


def load(p: Problem):
    return p.data(dtype=int)


if __name__ == '__main__':
    problem = Problem(25, test=False)

    print(part_a(*load(problem)))

    # problem.submit(part_a(*load(problem)), 'a')