from itertools import combinations

from utils.utils import load_input_file

starting_positions = load_input_file(12).read().splitlines()


class Moon(object):
    def __init__(self, x: int, y: int, z: int):
        self.position_vector = [x, y, z]
        self.velocity_vector = [0, 0, 0]

    def apply_gravity(self, other: list):
        for index, dimension in enumerate(self.position_vector):
            if dimension < other.position_vector[index]:
                self.velocity_vector[index] += 1
                other.velocity_vector[index] -= 1
            elif dimension > other.position_vector[index]:
                self.velocity_vector[index] -= 1
                other.velocity_vector[index] += 1

    def step(self):
        for index, velocity in enumerate(self.velocity_vector):
            self.position_vector[index] += velocity

    def get_energy(self):
        potential_energy = sum([abs(val) for val in self.position_vector])
        kinetic_energy = sum([abs(val) for val in self.velocity_vector])

        return potential_energy * kinetic_energy
Beispiel #2
0
from itertools import permutations

from utils.utils import load_input_file

computer_init = [int(code) for code in load_input_file(7).readline().split(",")]


def run_program(computer: list, inputs: list, outputs: list):
    index = 0

    while True:
        opcode, first_mode, second_mode = parse_operation(
            "{0:05d}".format(computer[index])
        )

        if opcode not in [1, 2, 3, 4, 5, 6, 7, 8, 99]:
            raise ValueError("Intcode computer failed. Diagnostic incomplete...")

        if opcode == 99:
            break

        first_idx = computer[index + 1]
        second_idx = computer[index + 2]
        third_idx = computer[index + 3]

        first_param = first_idx if first_mode else computer[first_idx]

        if opcode in [1, 2, 5, 6, 7, 8]:
            second_param = second_idx if second_mode else computer[second_idx]

        if opcode == 1:
from utils.growing_list import GrowingList
from utils.utils import load_input_file

computer_init = [
    int(code) for code in load_input_file(9).readline().split(",")
]


def run_program(computer: GrowingList, inputs: list, outputs: list):
    index = 0
    relative_offset = 0

    while True:
        opcode, first_mode, second_mode, third_mode = parse_operation(
            "{0:05d}".format(computer[index]))

        if opcode not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 99]:
            raise ValueError(
                "Intcode computer failed. Diagnostic incomplete...")

        if opcode == 99:
            break

        # Get indexes epending on the mode
        first_idx = (relative_offset + computer[index + 1]
                     if first_mode == 2 else computer[index + 1])
        second_idx = (relative_offset + computer[index + 2]
                      if second_mode == 2 else computer[index + 2])
        third_idx = (relative_offset + computer[index + 3]
                     if third_mode == 2 else computer[index + 3])
Beispiel #4
0
                                      last_coordinates[1] - step)
                                     for step in range(1, steps + 1)])
        elif direction == "U":
            self.coordinates.extend([(last_coordinates[0],
                                      last_coordinates[1] + step)
                                     for step in range(1, steps + 1)])
        elif direction == "L":
            self.coordinates.extend([(last_coordinates[0] - step,
                                      last_coordinates[1])
                                     for step in range(1, steps + 1)])
        elif direction == "R":
            self.coordinates.extend([(last_coordinates[0] + step,
                                      last_coordinates[1])
                                     for step in range(1, steps + 1)])

    def get_intersections(self, other):
        intersections = set(self.coordinates).intersection(
            set(other.coordinates))
        intersections.remove((0, 0))
        return intersections


input_file = load_input_file(3)
wire1 = Wire(input_file.readline().split(","))
wire2 = Wire(input_file.readline().split(","))

crossings = wire1.get_intersections(wire2)
distances = map(lambda tup: abs(tup[0]) + abs(tup[1]), crossings)

print("Closest distance to an intersection is {0}".format(min(distances)))
from utils.utils import get_angle, load_input_file

asteroid_map = load_input_file(10).readlines()


def get_asteroids(asteroid_map: list):
    asteroids = []
    for y, line in enumerate(asteroid_map):
        for x, character in enumerate(line):
            if character == "#":
                asteroids.append((x, y))

    return asteroids


asteroids = get_asteroids(asteroid_map)

max_observable = 0
station = None

for asteroid in asteroids:
    others = [ast for ast in asteroids if ast != asteroid]

    visible_asteroids = {get_angle(asteroid, other): other for other in others}

    if len(visible_asteroids) > max_observable:
        max_observable = len(visible_asteroids)
        station = asteroid

print(
    "Maximum observable asteroids is {0} at position {1}".format(
Beispiel #6
0
from utils.utils import load_input_file

space_image = load_input_file(8).readline()

PX_WIDTH = 25
PX_HEIGHT = 6
LAYER_SIZE = PX_WIDTH * PX_HEIGHT


def parse_space_image(img: str):
    space_img_list = list(map(int, space_image))

    return list([
        space_img_list[x:x + LAYER_SIZE]
        for x in range(0, len(space_img_list), LAYER_SIZE)
    ])


layers = parse_space_image(space_image)
layered_pixels = list(zip(*layers))

decoded_image = [
    str(next(x for x in pixel if x < 2)) for pixel in layered_pixels
]

# Print image (I switched colors because it looks better on my dark-themed console ;D)
print("Image decoded => ")
for line in [
        decoded_image[x:x + PX_WIDTH]
        for x in range(0, len(decoded_image), PX_WIDTH)
]:
from utils.utils import load_input_file
from collections import Counter

password_range = load_input_file(4).readline().split("-")

good_candidates = 0

for candidate in range(int(password_range[0]), int(password_range[1])):
    counter = Counter(str(candidate))
    if 2 not in counter.values():
        continue

    if not all(
            int(i) <= int(j) for i, j in zip(str(candidate),
                                             str(candidate)[1:])):
        continue

    good_candidates += 1

print("Number of password candidates is {0}".format(good_candidates))
import math

from utils.utils import load_input_file

modules_list = load_input_file(1).readlines()

total_fuel_requirements = 0

for module in modules_list:
    fuel_req = math.floor(float(module) / 3.0) - 2

    total_fuel_requirements += fuel_req

print("Total fuel requirements is {}".format(total_fuel_requirements))
from treelib import Tree

from utils.utils import load_input_file

orbit_map = {
    line.rstrip().split(")")[1]: line.rstrip().split(")")[0]
    for line in load_input_file(6).readlines()
}

# Build the orbit tree
tree = Tree()
tree.create_node("COM", "COM")

to_treat_nodes = ["COM"]

while len(to_treat_nodes) != 0:
    current_node = to_treat_nodes.pop()

    for orbit, center in orbit_map.items():
        if center == current_node:
            tree.create_node(orbit, orbit, parent=center)
            to_treat_nodes.append(orbit)

pertinent_paths = [
    path for path in tree.paths_to_leaves() if path[-1] in ["YOU", "SAN"]
]

# Get lowest common ancestor dsitance from COM
lowest_common_ancestor = 0
for idx, pair in enumerate(zip(*pertinent_paths)):
    if pair[0] != pair[1]: