Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day 1 2024 #176

Open
wants to merge 29 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.idea
.vscode
.ipynb_checkpoints
__pycache__
57 changes: 57 additions & 0 deletions solutions/2023/kws/aoc_2023_kws/day_09.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from functools import reduce

import click
from aoc_2023_kws.cli import main
from aoc_2023_kws.config import config
from aocd import submit


def calculate_differences(value_series):
differences = []
for i in range(len(value_series) - 1):
differences.append(value_series[i + 1] - value_series[i])
return differences


def find_order(value_series):
all_orders = [value_series]
while not all([f == 0 for f in value_series]):
value_series = calculate_differences(value_series)
all_orders.append(value_series)

return all_orders


@main.command()
@click.option("--sample", "-s", is_flag=True)
def day09(sample):
if sample:
input_data = (config.SAMPLE_DIR / "day09.txt").read_text()
else:
input_data = (config.USER_DIR / "day09.txt").read_text()

input_data = input_data.splitlines()
value_series = [[int(value) for value in line.split()] for line in input_data]

all_predictions = []
for vs in value_series:
fit = find_order(vs)
last_numbers = [f[-1] for f in fit]
all_predictions.append(sum(last_numbers))
print(fit, sum(last_numbers))
print()

print(f"Part 1: {sum(all_predictions)}")

all_predictions = []
for vs in value_series:
fit = find_order(vs)
first_numbers = [f[0] for f in fit]
first_numbers.reverse()
prediction = reduce(lambda x, y: y - x, first_numbers)
all_predictions.append(prediction)

print(fit, prediction)
print()

print(f"Part 2: {sum(all_predictions)}")
139 changes: 139 additions & 0 deletions solutions/2023/kws/aoc_2023_kws/day_10.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import math
from functools import cached_property
from typing import Dict, List, Tuple

import click
import numpy as np
from aoc_2023_kws.cli import main
from aoc_2023_kws.config import config
from aocd import submit

SEGMENTS = (
("|", {"N", "S"}),
("-", {"E", "W"}),
("L", {"N", "E"}),
("J", {"N", "W"}),
("7", {"S", "W"}),
("F", {"S", "E"}),
)
connections = {k: v for k, v in SEGMENTS}


class Pipe:
def __init__(self, x, y, char):
self.pos = x, y
self.char = char
self.connections = set()
self.level = None
if char in connections:
self.connections = connections[char]

@cached_property
def connected_tiles(self) -> Tuple[int, int]:
x, y = self.pos
tiles = []
if "N" in self.connections:
tiles.append((x, y - 1))
if "S" in self.connections:
tiles.append((x, y + 1))
if "W" in self.connections:
tiles.append((x - 1, y))
if "E" in self.connections:
tiles.append((x + 1, y))
return tuple(tiles)

def __repr__(self) -> str:
return f"Pipe({self.char}{self.pos}, {self.connections})"


@main.command()
@click.option("--sample", "-s", is_flag=True)
def day10(sample):
if sample:
input_data = (config.SAMPLE_DIR / "day10.txt").read_text()
else:
input_data = (config.USER_DIR / "day10.txt").read_text()

input_data = input_data.splitlines()
input_data = [list(line) for line in input_data]

pipes = []
for y, row in enumerate(input_data):
for x, char in enumerate(row):
if char == ".":
continue
else:
pipe = Pipe(x, y, char)
pipes.append(pipe)

all_connections: Dict[tuple, List[Pipe]] = {}
all_pipes = {p.pos: p for p in pipes}
start = None

for pipe in pipes:
for c in pipe.connected_tiles:
all_connections.setdefault(c, []).append(pipe)

if pipe.char == "S":
start = pipe

# Get all the pipes that are connected to any of the pipes in loop_pipes
def find_connections(loop_pipes, level):
new_pipes = []
for p in loop_pipes:
new_pipes.extend([all_pipes.get(c) for c in p.connected_tiles])
new_pipes = [p for p in new_pipes if p]
new_pipes = [p for p in new_pipes if p.level is None]
for p in new_pipes:
p.level = level
return new_pipes

loop_pipes = all_connections[start.pos]
for loop_pipe in loop_pipes:
loop_pipe.level = 1

new_pipes = loop_pipes
loop_pipes = [start] + loop_pipes
level = 2
while new_pipes:
new_pipes = find_connections(new_pipes, level)
loop_pipes.extend(new_pipes)
level += 1

print(max([p.level for p in loop_pipes]))

# F-7 = 2
# F-J = 1

# Part 2
matrix = np.array(input_data)
loop_coords = [p.pos for p in loop_pipes]
for y in range(matrix.shape[0]):
for x in range(matrix.shape[1]):
if (x, y) not in loop_coords:
matrix[y, x] = "."

for y in matrix:
print("".join(y))

print("\n\n")

inside_pieces = 0
replacement_values = {"F": -0.5, "J": -0.5, "7": 0.5, "L": 0.5, "|": 1}
for y in range(matrix.shape[0]):
for x in range(matrix.shape[1]):
if matrix[y, x] not in ".*":
continue

x_after = matrix[y, x:]
x_values = [replacement_values.get(c, 0) for c in x_after]
x_after_odd = math.floor(abs(sum(x_values))) % 2

if x_after_odd:
matrix[y, x] = " "
inside_pieces += 1

for y in matrix:
print("".join(y))

print(inside_pieces)
71 changes: 71 additions & 0 deletions solutions/2023/kws/aoc_2023_kws/day_11.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import click
import numpy as np
from aoc_2023_kws.cli import main
from aoc_2023_kws.config import config
from aocd import submit
from scipy.spatial.distance import pdist


@main.command()
@click.option("--sample", "-s", is_flag=True)
def day11(sample):
if sample:
input_data = (config.SAMPLE_DIR / "day11.txt").read_text()
else:
input_data = (config.USER_DIR / "day11.txt").read_text()

input_data = input_data.splitlines()
input_data = [list(line) for line in input_data]
orig_data = np.array(input_data)
input_data = orig_data.copy()

# Find the rows that only contain "." entries
rows_with_only_dots = np.all(input_data == ".", axis=1)
indices_of_rows_with_only_dots = np.where(rows_with_only_dots)[0]

# Find the columns that only contain "." entries
cols_with_only_dots = np.all(input_data == ".", axis=0)
indices_of_cols_with_only_dots = np.where(cols_with_only_dots)[0]

# Insert a column of "."s before each row
input_data = np.insert(input_data, indices_of_rows_with_only_dots, "x", axis=0)

# Insert a column of "."s before each column
input_data = np.insert(input_data, indices_of_cols_with_only_dots, "y", axis=1)

# Find the x, y coordinates of each '#'
coordinates = np.argwhere(input_data == "#")

# Calculate pairwise distances between coordinates
pairwise_distances = pdist(coordinates, metric="cityblock")

# Print the pairwise distances
print(pairwise_distances)
print(len(pairwise_distances))
print(sum(pairwise_distances))

test = [[0, 4], [11, 9]]
print(pdist(test, metric="cityblock"))

part2_data = orig_data.copy()
coordinates = np.argwhere(part2_data == "#")

scale = 1_000_000
# scale = 100

scale -= 1

print("Adjusted coordinates")
adjusted_coordinates = []
for x, y in coordinates:
cols = sum([1 for i in indices_of_cols_with_only_dots if i < y]) * scale
rows = sum([1 for i in indices_of_rows_with_only_dots if i < x]) * scale
if cols:
y += cols
if rows:
x += rows
print(x, y, cols, rows)
adjusted_coordinates.append([x, y])

pairwise_distances = pdist(adjusted_coordinates, metric="cityblock")
print(sum(pairwise_distances))
Loading