Example #1
0
def part1(data):
    # test job
    robot = Robot([], False)
    # replace the stdout from the program with a preplanned route
    robot.stdout = (
        v
        for v in [
            WHITE,
            0,  #
            BLACK,
            0,  #
            WHITE,
            0,  #
            WHITE,
            0,  #
            BLACK,
            1,  #
            WHITE,
            0,  #
            WHITE,
            0,
        ]
    )
    # we have to manually advance the camera output as no program will be asking for input
    camera = robot.Camera()
    for color, position in robot.Paint():
        next(camera)
    print(robot.hull)

    # actual paint job
    robot = Robot(data, False)
    for color, position in robot.Paint():
        pass

    util.Answer(1, len(robot.hull.canvas.keys()))
Example #2
0
def part2(data):
    results = {}
    for test in itertools.permutations([5, 6, 7, 8, 9]):
        thrust = AmplifyWithFeedback(data, test)
        results[thrust] = test
    maxthrust = max(results.keys())
    util.Answer(2, [maxthrust, results[maxthrust]])
Example #3
0
def part1(data):
    results = {}
    for test in itertools.permutations([0, 1, 2, 3, 4]):
        thrust = Amplify(data, test)
        results[thrust] = test
    maxthrust = max(results.keys())
    util.Answer(1, [maxthrust, results[maxthrust]])
Example #4
0
def part2(data):
    offset = int("".join(str(v) for v in data[:7]))
    message = []
    for i in range(10000):
        message += data
    print("Started 2")
    util.Answer(2, fft(message, offset))
Example #5
0
def part1(data):
    maze = Maze(data)

    nodes = build_graph(maze, "#", ".", True)

    # collect points of interest
    keys = {}
    doors = {}
    start = None
    for node in nodes.values():
        if node.value == "@":
            start = node.position
        elif node.value != ".":
            if IsKey(node.value):
                keys[node.value] = node.position
            elif IsDoor(node.value):
                doors[node.value] = node.position

    for node in nodes.values():
        print(node)

    keychain = []
    paths = find_keys(Path(nodes[start]), keychain)
    print("***", paths)
    # for path in paths:
    #     print(path.end.value, len(path))

    print("Solution")
    solutions = getsolutions(nodes[start], totalkeys=len(keys))

    util.Answer(1, min(solutions))
Example #6
0
def part2(data):
    puzzle = [
        "#########################################",
        "#       #         #         #   #     # #",
        "# ### ### # ##### # ####### ### # # # # #",
        "#   # #   #   #   #   #   #   #   # #   #",
        "### # # ##### ### ### ### ### ##### ### #",
        "#   # #   # #   #   #   #     #     #O  #",
        "# ####### # ### # ##### # ##### ####### #",
        "# #   #       # # #     #     # #     # #",
        "# # # # ####### # # ######### # # ### # #",
        "# # #     #     # # # #       #   # # # #",
        "# # ####### ##### # # # ####### ### # # #",
        "#   #     # #     # #   #     #     # # #",
        "# ### ### # # ##### # ### # ##### ### # #",
        "#   # # # # #   #   #   # # #     #   # #",
        "### # # # # ### # ##### # # # ##### ### #",
        "#   # # # # #   # #   # # #       # #   #",
        "# ### # # # # ### # ### # ######### # ###",
        "# # # #   # # # # #   # #   #       # # #",
        "# # # # ### # # # ### # ##### ####### # #",
        "# # # #   # #   #   #     #   #   #   # #",
        "# # # ### # ####### ##### # ### # # ### #",
        "#   # # # #       # # #   #   # #   #   #",
        "### # # # ####### # # # ### # ##### # # #",
        "#   # #         # # # # #   #     #   # #",
        "# ### ######### # # # # ### ##### ##### #",
        "#   #   # #   # # #   #   #     # #   # #",
        "### ### # # # # # ####### ##### # # # # #",
        "#     # #   #           #     # #   # # #",
        "# ##### ############### ##### ####### # #",
        "# #   #         #   # # #   # #   #   # #",
        "### # ######### # # # # # # # # # # #####",
        "#   #           # # # # # # #   # # #   #",
        "# ### ########### # # # # # ##### # # # #",
        "# #   #           # #   # #     # #   # #",
        "# ##### ########### # ### ##### # ##### #",
        "# #     #         # #   # # #   # #   # #",
        "# # ####### ##### # ##### # # ### # # # #",
        "#   #       #   # # #   # # # #   # #   #",
        "# ####### ### ### # # # # # # # ### ### #",
        "#         #       #   #     #       #   #",
        "#########################################",
    ]

    nodes = build_graph(Maze(puzzle), "#", " ", False)

    # find the start position
    start = None
    for node in nodes.values():
        if node.value == "O":
            start = node.position

    paths = get_child_paths(Path(nodes[start]))

    answer = max(len(path) for path in paths)
    util.Answer(2, answer)
    assert answer == 368
Example #7
0
def part1(perms):
    good = 0
    for perm in perms:
        for i in range(0, len(perm) - 1):
            if perm[i] == perm[i + 1]:
                good += 1
                break

    util.Answer(1, good)
Example #8
0
def part1(data):
    layers = separate_layers(data, 25, 6)

    values = {}

    for layer in layers:
        values[layer.count("0")] = layer.count("1") * layer.count("2")

    util.Answer(1, values[min(values.keys())])
Example #9
0
def part1(moons):
    system = OrbitalSystem(moons)

    for timestep in range(1000):
        system.step()

    energy = 0
    for moon in moons:
        energy += moon.energy

    util.Answer(1, energy)
Example #10
0
def part2(data):
    robot = Robot(data, False)

    # robot expects to start on a white panel
    robot.hull.paint(Coord(0, 0), WHITE)

    for color, position in robot.Paint():
        pass

    util.Answer(2, None)
    print(robot.hull)
Example #11
0
def part1(id):
    grid = makegrid(id)
    max = 0
    maxcell = None
    for x in range(1, 302 - 3):
        for y in range(1, 302 - 3):
            power = gridpower(x, y, 3, grid)
            if power > max:
                max = power
                maxcell = (x, y)
    util.Answer(1, maxcell)
Example #12
0
def part2(inputs: List[int]):
    freq = 0
    visited = {0: 1}
    while visited[freq] == 1:
        for inp in inputs:
            freq += inp
            if freq in visited:
                visited[freq] += 1
                break
            visited[freq] = 1
    util.Answer(2, freq)
Example #13
0
def part2(letters):
    letters = react(letters)  # start from the reacted string

    letter = None
    length = None
    for c in string.ascii_lowercase:
        tmp = list(l for l in letters if not same(l, c))
        count = len(react(tmp))
        if letter is None or count < length:
            letter = c
            length = count
    util.Answer(2, (letter, length))
Example #14
0
def part1(data):
    reactions = {}
    for reaction in data:
        reactions[reaction.result.element] = reaction

    ingredients = {"FUEL": OreQuantity("FUEL", 1)}
    while "ORE" not in ingredients or len(ingredients) > 1:
        ingredients = calc_ore(ingredients, reactions)

    print(ingredients)

    util.Answer(1, ingredients["ORE"])
Example #15
0
def part1(data):
    stdout = computer.Run(data)
    video = []
    line = []
    for out in stdout:
        if out == 10:
            video.append(line)
            line = []
        else:
            line.append(chr(out))

    util.Answer(1, compute_alignment(video))
Example #16
0
def part2(data):
    for noun in range(100):
        for verb in range(100):
            program = data[:]  # make a copy
            program[1] = noun
            program[2] = verb

            computer.Run(program)
            if program[0] == 19690720:
                util.Answer(
                    2, f"{100 * noun + verb} (noun: {noun}, verb: {verb})")
                break
Example #17
0
def part2(id):
    grid = makegrid(id)
    max = -9999999
    maxcell = None
    for cell in range(300, 1, -1):
        for x in range(1, 302 - cell):
            for y in range(1, 302 - cell):
                power = gridpower(x, y, cell, grid)
                if power > max:
                    max = power
                    maxcell = (x, y, cell)
        print(cell, maxcell, max)
    util.Answer(1, maxcell)
Example #18
0
def part1(inputs):
	patches = {}
	fabric = {}
	for (coordx, coordy), (dimx, dimy), patch in inputs:
		patches[patch] = {}
		for x in range(dimx):
			for y in range(dimy):
				inch = str(coordx+x) + "x" + str(coordy+y)
				if inch not in fabric:
					fabric[inch] = []
				fabric[inch].append(patch)
				patches[patch][inch] = fabric[inch]
	#print(patches)
	total = 0
	for v in fabric.values():
		if len(v) >= 2:
			total += 1
	util.Answer(1, total)
	
	for patch, inches in patches.items():
		if sum(1 for inch in inches.values() if len(inch) > 1) == 0:
			util.Answer(2, patch)
			break
Example #19
0
def part2(objects):
    you = objects["YOU"].orbitchain()
    san = objects["SAN"].orbitchain()

    santa = 0
    for i, obj in enumerate(you[2:]):
        try:
            santa = san.index(obj)
            print(i)
            break
        except:
            continue

    util.Answer(2, santa + i)
Example #20
0
def part1(data):

    program = [1, 1, 1, 4, 99, 5, 6, 0, 99]
    computer.Run(program)
    assert program[0] == 30

    program = [1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]
    computer.Run(program)
    assert program[0] == 3500

    program = data[:]
    computer.Run(program)

    util.Answer(1, program[0])
Example #21
0
def part2(inputs):
	for left in inputs:
		for right in inputs:
			if left == right:
				continue
			common = []
			for i in range(len(left)):
				if left[i] == right[i]:
					common.append(left[i])
				if len(common) < i:
					break
			if len(common) == len(left) - 1:
				util.Answer(2, "".join(common))
				return
Example #22
0
def part1(program):
    stdout = computer.Run(program, None)

    canvas = Canvas({0: " ", 1: "#", 2: "X", 3: "T", 4: "O"}, False)
    while True:
        try:
            pos = Coord(next(stdout), next(stdout))
            tile = next(stdout)
        except StopIteration:
            break

        canvas.paint(pos, tile)

    print(canvas)
    util.Answer(1, sum(1 for v in canvas.canvas.values() if v == 2))
Example #23
0
def part2(data, worker_count, extra_time, expected_answer=None):
	answer = expected_answer
	tasks = build_graph(data)
	completed = set()
	completing = []
	taskorder = ""
	elapsed = 0
	workers = []
	for i in range(worker_count):
		workers.append(Worker(extra_time))
		
	while len(completed) < len(tasks):
		# work work work
		working = sum(worker.working() for worker in workers)
		worker_stopped = False
		while working > 0 and not worker_stopped:
			elapsed += 1
			worker_stopped = (working != sum(worker.work() for worker in workers))

		# who finished working?		
		completing = []
		working = []
		for worker in workers:
			if not worker.working() and worker.task is not None:
				completing.append(worker.task)
				worker.assign(None)
			elif worker.working():
				working.append(worker.task)
		
		completing.sort()
		completed.update(completing)
		taskorder += "".join(completing)
		
		completing = []
		for task in tasks.values():
			if task.id not in completed \
				and task.id not in working \
				and len(task.parents - completed) == 0:
					completing.append(task.id)
		completing.sort()
		
		for worker in workers:
			if len(completing) > 0 and not worker.working():
				worker.assign(completing[0])
				completing = completing[1:]
		
	util.Answer(2, elapsed)
	assert elapsed == expected_answer
Example #24
0
def part2(perms):
    good = 0
    for perm in perms:
        for i in range(10):
            c = str(i)
            if c not in perm:
                continue
            count = 0
            for i in range(len(perm)):
                if perm[i] == c:
                    count += 1
            if count == 2:
                good += 1
                break

    util.Answer(2, good)
Example #25
0
def part1(data, expected_answer):
	tasks = build_graph(data)
	completed = set()
	completing = []
	taskorder = ""
		
	while len(completed) < len(tasks):
		completing = []
		for task in tasks.values():
			if task.id not in completed and len(task.parents - completed) == 0:
				completing.append(task.id)
		
		completing.sort()
		completed.update(completing[0])
		taskorder += completing[0]
	assert taskorder.upper() == expected_answer
	util.Answer(1, taskorder.upper())
Example #26
0
def part1(data):
    coords = []
    effects = []
    canvas = Canvas({0: " ", 1: "#"}, inverted=False)
    for x in range(50):
        for y in range(50):
            coord = Coord(x, y)
            stdout = computer.Run(data[:], stdin(coord))
            coords.append(coord)
            effects.append(next(stdout))

            canvas.paint(coord, effects[-1])
        print(x)
    zip(coords, effects)

    util.Answer(1, sum(effects))

    print(canvas)
Example #27
0
def part2(data):
    layers = separate_layers(data, 25, 6)

    image = ["2"] * (25 * 6)
    for layer in layers:
        for i in range(25 * 6):
            if layer[i] == "0":
                if image[i] == "2":
                    image[i] = " "
            elif layer[i] == "1":
                if image[i] == "2":
                    image[i] = "#"

    util.Answer(2, None)

    print("-" * 25)
    for offset in range(0, 25 * 6, 25):
        print("".join(image[offset:offset + 25]))
    print("-" * 25)
Example #28
0
def part1(inputs):
	two = 0
	three = 0
	for inp in inputs:
		counts = {}
		for l in inp:
			if l not in counts:
				counts[l] = 0
			counts[l] += 1
		hasTwo = False
		hasThree = False
		for count in counts.values():
			hasTwo |= (count == 2)
			hasThree |= (count == 3)

		two += hasTwo
		three += hasThree

	util.Answer(1, two*three)
Example #29
0
def part2(data):
    data[0] = 2  # wake up robot

    "LR8|L10", "R", "10", "L", "8"

    "R", "12", "L", "10", "R", "10",
    "L", "2", "R", "12", "L", "6"

    # A------
    "R", "12", "L", "10", "R", "12",  # A
    "L", "8", "R", "10", "R", "6",
    "R", "12", "L", "10", "R", "12",  # A
    "R", "12", "L", "10", "R", "10",  # A
    "L", "8",
    "L", "8", "R", "10", "R", "6",
    "R", "12", "L", "10", "R", "10",
    "L", "8",
    "L", "8", "R", "10", "R", "6",
    "R", "12", "L", "10", "R", "10",

    program = [
        "A,B,C,A,B,A,B",  # program sequence (A,B,C)
        "R,12,L",  # program A
        "10,R,12",  # program B
        "L,8,R,10,R,6",  # program C
        "n\n",  # video feed
    ]

    stdout = computer.Run(data, (ord(v) for v in "\n".join(program)))

    line = []
    for out in stdout:
        if out == 10:
            if len(line) == 0:
                print("")  # system('cls')
            else:
                print("".join(line))
            line = []
        else:
            line.append(chr(out))
    util.Answer(2, None)
Example #30
0
def part2(moons):
    system = OrbitalSystem(moons)

    # this is just to see the periods on each axis
    while True and system.time < 231615:
        system.step()

        for axis in ["x", "y", "z"]:
            allequal = True
            for i in range(system.count):
                allequal &= (system.objects[i].position.__dict__[axis] ==
                             system._orig[i].position.__dict__[axis])
            if allequal:
                print(axis, system.time)
        # print(system.time, system.objects[0].position.x, system.objects[0].position.y, system.objects[0].position.z)

        if system.time % 10000 == 0:
            pass  # print(f"Time:{system.time:,}")

    print("periods: (x: 84032, y: 231614, z: 193052)")
    print("used a LCM (Least Common Multiple) calculator to find below")
    util.Answer(2, 469671086427712)