Beispiel #1
0
def get_score(game):
    players, marbles = parse_game(game)
    game = Game()
    pos = 0     # position of last placed marble.
    scores = dict()

    for i in range(marbles):
        p = (i % players) + 1   # 1-indexed
        m = i + 1               # marble value
        game_size = game.size()

        if i != 0 and i % 100000 == 0:
            print("loop", i, "done: ", int(m/marbles * 100), "%", get_time(start))

        # Special cases.
        if m % 23 == 0:
            # now find the marble 7 steps left. or it's position.
            pos = (game_size + pos - 7) % game_size
            # add score of marble + the pos 7 left.
            scores = add_score(scores, p, m + game.get(pos))
            game.remove(pos)
        else:
            pos = ((pos + 1) % game_size) + 1
            game.add(pos, m)

    return max(scores.items(), key=operator.itemgetter(1))[1]
Beispiel #2
0
def run_compiled_code(input_path, output_dir_path, args, stdin):
    '''
    Run complied c source code executable.

    Arguments:
        input_path {str} -- File path of compiled c source code
        output_dir_path {str} -- File path to store `time` command output
        args {list} -- Arguments required to run c program
        stdin {list} -- Passwords required to run c program

    Returns:
        float -- [description]
    '''
    input_file = fs.details(input_path)
    run_output_file = FILE_NAME['run'].format(name=input_file['name'])
    run_output_file_path = os.path.join(output_dir_path, run_output_file)

    execute = CMD['run'].format(input=input_path,
                                args=' '.join(args),
                                stdin='\n'.join(stdin))
    time = CMD['time'].format(cmd=execute, output=run_output_file_path)
    cmd = CMD['bash'].format(time)
    output = str(os.popen(cmd).read())
    content = fs.read(run_output_file_path)
    print(output)

    return {
        'time-taken': get_time(content),
    }
Beispiel #3
0
            pos = (game_size + pos - 7) % game_size
            # add score of marble + the pos 7 left.
            scores = add_score(scores, p, m + game.get(pos))
            game.remove(pos)
        else:
            pos = ((pos + 1) % game_size) + 1
            game.add(pos, m)

    return max(scores.items(), key=operator.itemgetter(1))[1]


def add_score(scores, p, v):
    if p in scores:
        scores[p] = scores[p] + v
    else:
        scores[p] = v
    return scores


if __name__ == "__main__":
    with open('input/day09.txt') as f:
        lines = f.read().splitlines()
        part1 = lines[0]
        part2 = lines[1]

    start = timer()
    print("result day 09 part 1: ", get_score(part1), " in ", get_time(start))

    start = timer()
    print("result day 09 part 2: ", get_score(part2), " in ", get_time(start))
Beispiel #4
0
from utils.time import get_time


def parse_answer_anyone(answer):
    return set(answer.replace("\n", "").strip())


def parse_answer_everyone(answer):
    everyone = len(answer.splitlines())
    chars = answer.replace("\n", "").strip()
    return [c for c in set(chars) if chars.count(c) == everyone]


def count_sums(answers):
    return sum([len(a) for a in answers])


if __name__ == "__main__":
    with open('input/day06.txt') as f:
        answers = f.read().split("\n\n")

    start = timer()
    answers_anyone = [parse_answer_anyone(a) for a in answers]
    print("result day 06 part 1: {} in {}".format(count_sums(answers_anyone),
                                                  get_time(start)))

    start = timer()
    answers_everyone = [parse_answer_everyone(a) for a in answers]
    print("result day 06 part 2: {} in {}".format(count_sums(answers_everyone),
                                                  get_time(start)))
Beispiel #5
0
def is_valid(password):
    char_min, char_max, char, password = password
    char_curr = password.count(char)
    return char_min <= char_curr and char_max >= char_curr


def valid_passwords(passwords):
    return len([p for p in passwords if is_valid(p)])


def is_valid_toboggan(password):
    pos_1, pos_2, char, password = password
    return (password[pos_1 - 1] == char) != (password[pos_2 - 1] == char)


def valid_passwords_toboggan(passwords):
    return len([p for p in passwords if is_valid_toboggan(p)])


if __name__ == "__main__":
    with open('input/day02.txt') as f:
        passwords = [parse_password(p) for p in f.read().splitlines()]

    start = timer()
    print("result day 02 part 1: {} in {}".format(valid_passwords(passwords),
                                                  get_time(start)))

    start = timer()
    print("result day 02 part 2: {} in {}".format(
        valid_passwords_toboggan(passwords), get_time(start)))
Beispiel #6
0
        for c in self.child_nodes:
            met += c.get_metadata()
        return met

    def get_value(self):
        if self.qty_child < 1:
            return sum(self.metadata)
        else:
            val = 0
            for m in self.metadata:  # m is the index of child + 1.
                if self.qty_child > m - 1:
                    val += self.child_nodes[m - 1].get_value()
            return val


def get_nodes(license):
    return Node(list(map(int, license.split(" "))))


if __name__ == "__main__":
    with open('input/day08.txt') as f:
        params = f.read().splitlines()[0]

    start = timer()
    nodes = get_nodes(params)
    print("result day 08 part 1: ", sum(nodes.get_metadata()), " in ",
          get_time(start))

    start = timer()
    print("result day 08 part 2: ", nodes.get_value(), " in ", get_time(start))
Beispiel #7
0
            last = polymer
        else:
            break

    return polymer


# return a set of all unique units (just lowercase)
def get_units(polymer):
    return set(polymer.lower())


def remove(polymer, unit):
    p = polymer.replace(unit, "").replace(unit.swapcase(), "")
    return len(react(p))


def shortest(polymer):
    return min([remove(polymer, x) for x in get_units(polymer)])


if __name__ == "__main__":
    with open('input/day05.txt') as f:
        params = f.read().splitlines()[0]

    start = timer()
    print("result day 05 part 1: ", len(react(params)), " in ", get_time(start))

    start = timer()
    print("result day 05 part 2: ", shortest(params), " in ", get_time(start))
Beispiel #8
0

# compare all grids to all others and store unique intersection
def duplicates(grids):
    return [coo for coo, v in grids.items() if len(v) > 1]


# unique grid simply mean non of the coordinates we had in duplicates.
def unique(grids):
    ids = set()
    bad = set()
    for coo, v in grids.items():
        ids = ids | set(v)
        if len(v) > 1:
            bad = bad | set(v)
    return ids.difference(bad).pop()


if __name__ == "__main__":
    with open('input/day03.txt') as f:
        params = f.read().splitlines()

    start = timer()
    grids = get_grids(params)
    print("got grids ", len(grids), " in ", get_time(start))
    start = timer()
    print("result day 03 part 1: ", len(duplicates(grids)), " in ",
          get_time(start))
    start = timer()
    print("result day 03 part 2: ", unique(grids), " in ", get_time(start))
Beispiel #9
0
        for t in ts:
            if is_alone(t, ts):
                alone = True
                break

        if alone:
            continue
        else:
            print("Message shown after ", step, " seconds.")
            break

    min_x, min_y, max_x, max_y = get_limits(ts)
    ret = ""
    for x in range(min_x, max_x + 1):
        for y in range(min_y, max_y + 1):
            if (x, y) in ts:
                ret += "#"
            else:
                ret += "."
        ret += "\n"
    return ret


if __name__ == "__main__":
    with open('input/day10.txt') as f:
        lines = f.read().splitlines()

    start = timer()
    print("result day 10 part 1+2: \n")
    print(sky(get_points(lines)), " in ", get_time(start))
Beispiel #10
0
# Create an (inverted) mask of the diff. 0 means match, 1 means drop
def diff_mask(box_a, box_b):
    return [0 if x == y else 1 for x, y in zip(box_a, box_b)]


# get the match according to mask.
def unmask(box, mask):
    return "".join(v for m, v in zip(mask, box) if m != v)


if __name__ == "__main__":
    with open('input/day02.txt') as f:
        params = f.read().splitlines()

    start = timer()
    print("result day 02 part 1: ", list_checksum(params), " in ", get_time(start))
    start = timer()
    print("result day 02 part 2: ", diff_one(set(params)), " in ", get_time(start))

    # Speed measurement, python is way faster working on sets than on lists.
    #for i in range(10):
    #    start = timer()
    #    print("[", i, "] result day 02 part 2: ", diff_one(params), " in ", get_time(start))
    #
    #paramset = set(params)
    #for i in range(10):
    #    start = timer()
    #    print("[", i, "] result day 02 part 2 with set: ", diff_one(paramset), " in ", get_time(start))
    #
Beispiel #11
0
    max_x = len(geo[0])
    max_y = len(geo)

    if curr_y >= max_y:
        return acc

    if geo[curr_y][curr_x % max_x] == TREE:
        acc += 1

    return count_trees(geo, curr_x + slope_x, curr_y + slope_y, acc, slope_x,
                       slope_y)


if __name__ == "__main__":
    with open('input/day03.txt') as f:
        geo = f.read().splitlines()

    start = timer()
    print("result day 03 part 1: {} in {}".format(count_trees(geo),
                                                  get_time(start)))

    start = timer()
    slope_1 = count_trees(geo, slope_x=1, slope_y=1)
    slope_2 = count_trees(geo, slope_x=3, slope_y=1)
    slope_3 = count_trees(geo, slope_x=5, slope_y=1)
    slope_4 = count_trees(geo, slope_x=7, slope_y=1)
    slope_5 = count_trees(geo, slope_x=1, slope_y=2)

    print("result day 03 part 2: {} in {}".format(
        (slope_1 * slope_2 * slope_3 * slope_4 * slope_5), get_time(start)))
Beispiel #12
0
        else:
            row = int(RE_MEM_LINE.findall(target)[0])
            mem[row] = mask_dec(int(value), mask)
    return sum(mem.values())


def run_mad(program: str) -> int:
    mask = None
    mem = {}
    for line in program:
        target, value = line.split(" = ")
        if target == 'mask':
            mask = value
        else:
            row = int(RE_MEM_LINE.findall(target)[0])
            addresses = mask_mem(int(row), mask)
            for address in addresses:
                mem[address] = int(value)
    return sum(mem.values())


if __name__ == "__main__":
    with open('input/day14.txt') as f:
        program = f.read().splitlines()

    start = timer()
    print("result day 14 part 1: {} in {}".format(run_program(program), get_time(start)))

    start = timer()
    print("result day 14 part 2: {} in {}".format(run_mad(program), get_time(start)))
Beispiel #13
0
    return list(set(bags))


def can_carry(tree, color="shiny gold"):
    # simplify the tree to a color tree for speed.
    color_tree = {}
    for bag in tree:
        color_tree[bag] = [color for color, count in tree[bag]]
    return set(get_carrier(color_tree, color))


def count_children(tree, color):
    cnt = 1
    for child_color, count in tree[color]:
        cnt += int(count) * count_children(tree, child_color)
    return cnt


if __name__ == "__main__":
    with open('input/day07.txt') as f:
        rules = f.read().splitlines()

    start = timer()
    tree = build_tree(rules)
    print("result day 07 part 1: {} in {}".format(
        len(can_carry(tree, "shiny gold")), get_time(start)))

    start = timer()
    print("result day 07 part 2: {} in {}".format(
        count_children(tree, "shiny gold") - 1, get_time(start)))
Beispiel #14
0
        pos = (direction, x + (value * w_x), y + (value * w_y))
    elif action in ['L', 'R']:
        waypoint = turn_waypoint(waypoint, action, value)
    return pos, waypoint


def navigate_waypoint(instructions):
    pos = ('E', 0, 0)  # facing east, position 0, 0
    waypoint = (1, 10)  # 1 north, 10 east
    for instruction in parse_instructions(instructions):
        pos, waypoint = step_waypoint(pos, waypoint, instruction)
    return pos


def distance_waypoint(instructions):
    _, x, y = navigate_waypoint(instructions)
    return abs(x) + abs(y)


if __name__ == "__main__":
    with open('input/day12.txt') as f:
        nav_instructions = f.read().splitlines()

    start = timer()
    print("result day 12 part 1: {} in {}".format(distance(nav_instructions),
                                                  get_time(start)))

    start = timer()
    print("result day 12 part 2: {} in {}".format(
        distance_waypoint(nav_instructions), get_time(start)))
Beispiel #15
0
                return number


def chunk_list(lst, size):
    return [lst[i:i + size] for i in range(0, len(lst), size)]


def find_contigous(numbers, target):
    for i in range(2, len(numbers) - 1):
        for offset in range(0, i):
            sets = chunk_list(numbers[offset:], i)
            for s in sets:
                if len(s) > 1:
                    if sum(s) == target:
                        return min(s) + max(s)


if __name__ == "__main__":
    with open('input/day09.txt') as f:
        numbers = f.read().splitlines()

    numbers = list(map(int, numbers))

    start = timer()
    target = find_first(numbers, 25)
    print("result day 09 part 1: {} in {}".format(target, get_time(start)))

    start = timer()
    print("result day 09 part 2: {} in {}".format(
        find_contigous(numbers, target), get_time(start)))
Beispiel #16
0
        if not byr(p['byr']):
            continue
        if not iyr(p['iyr']):
            continue
        if not eyr(p['eyr']):
            continue
        if not hgt(p['hgt']):
            continue
        if not hcl(p['hcl']):
            continue
        if not ecl(p['ecl']):
            continue
        if not pid(p['pid']):
            continue
        cnt += 1
    return cnt


if __name__ == "__main__":
    with open('input/day04.txt') as f:
        passports = f.read().split("\n\n")
    passports = [parse_passport(p) for p in passports]

    start = timer()
    print("result day 04 part 1: {} in {}".format(
        p1_valid_passports(passports), get_time(start)))

    start = timer()
    print("result day 04 part 2: {} in {}".format(
        p2_valid_passports(passports), get_time(start)))
Beispiel #17
0
# Return the minute this guard slept the most.
def top_minute(logs, guard):
    return max(logs[guard].items(), key=operator.itemgetter(1))[0]


# Return id of the guard with max frequence.
def max_freq(logs):
    dmax = dict()
    for g in logs:
        dmax[g] = max(logs[g].values())

    return max(dmax.items(), key=operator.itemgetter(1))[0]


if __name__ == "__main__":
    with open('input/day04.txt') as f:
        params = f.read().splitlines()

    start = timer()
    logs = read_log(params)
    sleep_guard = max_sleep(logs)
    sleep_minute = top_minute(logs, sleep_guard)
    print("result day 04 part 1: guard: ", sleep_guard, " minute: ", sleep_minute, " answer: ",
          sleep_guard * sleep_minute, " in ", get_time(start))
    start = timer()
    freq_guard = max_freq(logs)
    freq_minute = top_minute(logs, freq_guard)
    print("result day 04 part 2: guard: ", freq_guard, " minute: ", freq_minute, " answer: ",
          freq_guard * freq_minute, " in ", get_time(start))
Beispiel #18
0
def find_iter(arr, size, target=2020):
    for combination in combinations(arr, size):
        if sum(combination) == target:
            return combination


if __name__ == "__main__":
    with open('input/day01.txt') as f:
        expense_report = [int(m) for m in f.read().splitlines()]
    expense_report.sort()

    start = timer()
    (x, y) = find_pair(expense_report)
    print("result day 01 part 1: pair={}, product={} in {}".format(
        (x, y), x * y, get_time(start)))

    start = timer()
    (x, y, z) = find_triple(expense_report)
    print("result day 01 part 2: triple={}, product={} in {}".format(
        (x, y, z), x * y * z, get_time(start)))

    # using itertools. slower but cleaner.
    (x, y) = find_iter(expense_report, 2)
    print("result day 01 part 1 using itertools: pair={}, product={} in {}".
          format((x, y), x * y, get_time(start)))

    start = timer()
    (x, y, z) = find_iter(expense_report, 3)
    print("result day 01 part 2 using itertools: triple={}, product={} in {}".
          format((x, y, z), x * y * z, get_time(start)))
Beispiel #19
0
    step_buses = [target_bus]
    is_valid = False
    while not is_valid:
        is_valid = True  # think positive!
        step = get_step(step_buses)
        time = time + step
        for bus_id in bus_ids:
            bus_t = time + bus_offsets[bus_id]
            if bus_t % bus_id == 0:
                if bus_id not in step_buses:
                    step_buses.append(bus_id)
            else:
                is_valid = False
                break
        if is_valid:
            break
    return time


if __name__ == "__main__":
    with open('input/day13.txt') as f:
        notes = f.read().splitlines()

    start = timer()
    print("result day 13 part 1: {} in {}".format(find_earliest_bus(notes),
                                                  get_time(start)))

    start = timer()
    print("result day 13 part 2: {} in {}".format(
        find_sequence_timestamp(notes[1]), get_time(start)))
Beispiel #20
0
    # try changing one jmp/nop at a time and run to see if it exists normally.
    normal_exit = False
    pos = 0
    result = 0
    while not normal_exit:
        op, arg = program[pos]
        new_program = program.copy()
        if op == "jmp":
            new_program[pos] = ("nop", arg)
            result, normal_exit = run(new_program)
        elif op == "nop":
            new_program[pos] = ("jmp", arg)
            result, normal_exit = run(new_program)
        pos = pos + 1
    return result


if __name__ == "__main__":
    with open('input/day08.txt') as f:
        instructions = f.read().splitlines()

    start = timer()
    program = parse_instructions(instructions)
    result, _ = run(program)
    print("result day 07 part 1: {} in {}".format(result, get_time(start)))

    start = timer()
    program = parse_instructions(instructions)
    print("result day 07 part 2: {} in {}".format(run_fixed(program),
                                                  get_time(start)))
Beispiel #21
0
    return sum(params_as_int(parameters))


# Return the first value we'll reach twice.
def twice(parameters):
    values = params_as_int(parameters)
    pos = 0
    result = 0
    history = set()
    history.add(0)

    while True:
        pos = pos % len(values)
        result = values[pos] + result

        if result in history:
            return result
        else:
            pos = pos + 1
            history.add(result)


if __name__ == "__main__":
    with open('input/day01.txt') as f:
        params = f.read().splitlines()

    start = timer()
    print("result day 01 part 1: ", sum_array(params), " in ", get_time(start))
    start = timer()
    print("result day 01 part 2: ", twice(params), " in ", get_time(start))
Beispiel #22
0
                if len(set(v) - set(done)) == 0:
                    o += k
        o.sort()

        # Add work if we have free workers.
        while len(w) < workers and len(o) > 0:
            job = o[0]
            w[job] = offset + get_char_time(job)
            o.remove(job)

        print("time:", time, " w: ", w, " done: ", "".join(done))
    return time, "".join(done)


def get_char_time(c):
    return ord(c) - 64


if __name__ == "__main__":
    with open('input/day07.txt') as f:
        params = f.read().splitlines()

    start = timer()
    instructions = read_inst(params)
    print("result day 07 part 1: ", timed_order_inst(instructions), " in ",
          get_time(start))

    start = timer()
    print("result day 07 part 2: ", timed_order_inst(instructions, 5, 60),
          " in ", get_time(start))