Skip to content

Commit

Permalink
Merge branch 'main' into day4
Browse files Browse the repository at this point in the history
  • Loading branch information
Colin Sullivan committed Dec 5, 2023
2 parents 918cc20 + f564d01 commit cbf61e4
Show file tree
Hide file tree
Showing 11 changed files with 467 additions and 10 deletions.
140 changes: 140 additions & 0 deletions data/day3.txt

Large diffs are not rendered by default.

55 changes: 46 additions & 9 deletions docs/docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ $ aoc [OPTIONS] COMMAND [ARGS]...

* `day1`: Command for running day1 stars
* `day2`: Command for running day2 stars
* `day3`: Command for running day3 stars
* `day4`: Command for running day4 stars
* `debug-version-info`: Print debug information to terminal.

Expand Down Expand Up @@ -132,14 +133,14 @@ $ aoc day2 part2 [OPTIONS] [INPUT_PATH]

* `--help`: Show this message and exit.

## `aoc day4`
## `aoc day3`

Command for running day4 stars
Command for running day3 stars

**Usage**:

```console
$ aoc day4 [OPTIONS] COMMAND [ARGS]...
$ aoc day3 [OPTIONS] COMMAND [ARGS]...
```

**Options**:
Expand All @@ -148,27 +149,63 @@ $ aoc day4 [OPTIONS] COMMAND [ARGS]...

**Commands**:

* `part1`: Calculate the sum of all the scratch card...
* `part2`: Count the total number of scratch cards
* `part1`: Calculate the sum of engine parts.
* `part2`: Calculate the sum of all gears

### `aoc day4 part1`
### `aoc day3 part1`

Calculate the sum of all the scratch card scores
Calculate the sum of engine parts.

**Usage**:

```console
$ aoc day4 part1 [OPTIONS] [INPUT_PATH]
$ aoc day3 part1 [OPTIONS] [INPUT_PATH]
```

**Arguments**:

* `[INPUT_PATH]`: Path to file containing the input [default: data/day4.txt]
* `[INPUT_PATH]`: Path to file containing the input [default: data/day3.txt]

**Options**:

* `--help`: Show this message and exit.

### `aoc day3 part2`

Calculate the sum of all gears

**Usage**:

```console
$ aoc day3 part2 [OPTIONS] [INPUT_PATH]
```

**Arguments**:

* `[INPUT_PATH]`: Path to file containing the input [default: data/day3.txt]

**Options**:

* `--help`: Show this message and exit.

## `aoc day4`

Command for running day4 stars

**Usage**:

```console
$ aoc day4 [OPTIONS] COMMAND [ARGS]...
```

**Options**:

* `--help`: Show this message and exit.

**Commands**:

* `part2`: Count the total number of scratch cards

### `aoc day4 part2`

Count the total number of scratch cards
Expand Down
1 change: 1 addition & 0 deletions docs/docs/day3/part1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
## ::: aoc.day3.part1
1 change: 1 addition & 0 deletions docs/docs/day3/part2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
## ::: aoc.day3.part2
4 changes: 4 additions & 0 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@ nav:
- Day 2:
- Part 1: day2/part1.md
- Part 2: day2/part2.md
- Day 3:
- Part 1: day3/part1.md
- Part 2: day3/part2.md
- Day 4:
- Part 1: day4/part1.md
- Part 2: day4/part2.md


theme:
name: "material"
font:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "aoc"
version = "0.2.0"
version = "0.3.0"
description = "Record of current and past attempts at Advent-of-Code in Python"
authors = ["Colin Sullivan <[email protected]>"]
readme = "README.md"
Expand Down
42 changes: 42 additions & 0 deletions src/aoc/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from aoc.day1.part2 import word_calibration_sum
from aoc.day2.part1 import sum_valid_game_ids
from aoc.day2.part2 import sum_game_powers
from aoc.day3.part1 import sum_part_numbers
from aoc.day3.part2 import sum_gear_ratios
from aoc.day4.part1 import card_points
from aoc.day4.part2 import count_cards

Expand Down Expand Up @@ -146,6 +148,40 @@ def day2part2(

cli.add_typer(day2app, name="day2")

day3app = typer.Typer(
help="Command for running day3 stars",
rich_markup_mode="rich",
)


@day3app.command(name="part1")
def day3part1(
input_path: Path = typer.Argument(
Path("data/day3.txt"), help="Path to file containing the input"
),
) -> None:
"""Calculate the sum of engine parts."""
with open(input_path) as infile:
input_text = infile.read()
total_sum = sum_part_numbers(input_text)
print(f"The sum of the engine parts is: [bold red]{total_sum}[/bold red]")


@day3app.command(name="part2")
def day3part2(
input_path: Path = typer.Argument(
Path("data/day3.txt"), help="Path to file containing the input"
),
) -> None:
"""Calculate the sum of all gears"""
with open(input_path) as infile:
input_text = infile.read()
total_sum = sum_gear_ratios(input_text)
print(f"The sum of the gear ratios is: [bold red]{total_sum}[/bold red]")


cli.add_typer(day3app, name="day3")

day4app = typer.Typer(
help="Command for running day4 stars",
rich_markup_mode="rich",
Expand All @@ -165,6 +201,12 @@ def day4part1(
print(f"The sum of card scores is: [bold red]{total_sum}[/bold red]")


day4app = typer.Typer(
help="Command for running day4 stars",
rich_markup_mode="rich",
)


@day4app.command(name="part2")
def day4part2(
input_path: Path = typer.Argument(
Expand Down
Empty file added src/aoc/day3/__init__.py
Empty file.
122 changes: 122 additions & 0 deletions src/aoc/day3/part1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
"""
# Day 3: Gear Ratios
You and the Elf eventually reach a gondola lift station; he says the gondola lift will take you up to the water source, but this is as far as he can bring you. You go inside.
It doesn't take long to find the gondolas, but there seems to be a problem: they're not moving.
"Aaah!"
You turn around to see a slightly-greasy Elf with a wrench and a look of surprise. "Sorry, I wasn't expecting anyone! The gondola lift isn't working right now; it'll still be a while before I can fix it." You offer to help.
The engineer explains that an engine part seems to be missing from the engine, but nobody can figure out which one. If you can add up all the part numbers in the engine schematic, it should be easy to work out which part is missing.
The engine schematic (your puzzle input) consists of a visual representation of the engine. There are lots of numbers and symbols you don't really understand, but apparently any number adjacent to a symbol, even diagonally, is a "part number" and should be included in your sum. (Periods (.) do not count as a symbol.)
Here is an example engine schematic:
```
467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..
```
In this schematic, two numbers are not part numbers because they are not adjacent to a symbol: 114 (top right) and 58 (middle right). Every other number is adjacent to a symbol and so is a part number; their sum is 4361.
Of course, the actual engine schematic is much larger. What is the sum of all of the part numbers in the engine schematic?
"""
from collections.abc import Iterable
from dataclasses import dataclass


@dataclass
class Number:
"""Dataclass for containing a number and it's position"""

value: int
row: int
columns: list[int]

def __hash__(self) -> int:
"""The hash of a Number is its position. Used for making it possible to use as a key in a dictionary"""
return hash(f"{self.row}, {self.columns}")


@dataclass
class Part:
"""Dataclass for storing the position of a engine number"""

row: int
column: int

def valid_coodinates(self) -> Iterable[tuple[int, int]]:
"""Get an iterable of valid positions for engine numbers
Returns:
A generator of position tuples for valid engine numbers
"""
for j in range(self.column - 1, self.column + 2):
for i in range(self.row - 1, self.row + 2):
yield (i, j)


def sum_part_numbers(input_text: str) -> int: # noqa C901
"""Get the sum of all the valid engine numbers that are adjacent or diagonal to a engine part.
Traverse the grid to accumulate engine numbers and parts and making a lookup from coordinates to engine numbers.
For each part search the lookup for using it's position for valid engine numbers and at them to the set. Return the sum.
Args:
input_text: Raw input string
Returns:
sum of all valid engine numbers
"""

parts = []
coords = {}

lines = input_text.splitlines()
for i, line in enumerate(lines):
num = ""
cols = []
for j, char in enumerate(line):
if char.isdigit():
num += char
cols.append(j)
elif char != ".":
parts.append(Part(i, j))
if num != "":
n = Number(int(num), i, cols)
for col in cols:
coords[(i, col)] = n
num = ""
cols = []
else:
if num != "":
n = Number(int(num), i, cols)
for col in cols:
coords[(i, col)] = n
num = ""
cols = []
if num != "":
n = Number(int(num), i, cols)
for col in cols:
coords[(i, col)] = n
num = ""
cols = []

valid_parts = set()
for part in parts:
for valid_coord in part.valid_coodinates():
if valid_coord in coords:
valid_parts.add(coords[valid_coord])

return sum(part.value for part in valid_parts)
89 changes: 89 additions & 0 deletions src/aoc/day3/part2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""The engineer finds the missing part and installs it in the engine! As the engine springs to life, you jump in the closest gondola, finally ready to ascend to the water source.
You don't seem to be going very fast, though. Maybe something is still wrong? Fortunately, the gondola has a phone labeled "help", so you pick it up and the engineer answers.
Before you can explain the situation, she suggests that you look out the window. There stands the engineer, holding a phone in one hand and waving with the other. You're going so slowly that you haven't even left the station. You exit the gondola.
The missing part wasn't the only issue - one of the gears in the engine is wrong. A gear is any * symbol that is adjacent to exactly two part numbers. Its gear ratio is the result of multiplying those two numbers together.
This time, you need to find the gear ratio of every gear and add them all up so that the engineer can figure out which gear needs to be replaced.
Consider the same engine schematic again:
```
467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..
```
In this schematic, there are two gears. The first is in the top left; it has part numbers 467 and 35, so its gear ratio is 16345. The second gear is in the lower right; its gear ratio is 451490. (The * adjacent to 617 is not a gear because it is only adjacent to one part number.) Adding up all of the gear ratios produces 467835.
What is the sum of all of the gear ratios in your engine schematic?
"""
from aoc.day3.part1 import Number, Part


def sum_gear_ratios(input_text: str) -> int: # noqa C901
"""Get the sum of all the gear ratios.
Traverse the grid to accumulate engine numbers and gears and making a lookup from coordinates to engine numbers.
For each gear search the lookup for using it's position for valid engine numbers and if there are exactly 2 add them to a set. Return the sum.
Args:
input_text: Raw input string
Returns:
sum of all valid gear ratios"""

parts = []
coords = {}

lines = input_text.splitlines()
for i, line in enumerate(lines):
num = ""
cols = []
for j, char in enumerate(line):
if char.isdigit():
num += char
cols.append(j)
elif char == "*":
parts.append(Part(i, j))
if num != "":
n = Number(int(num), i, cols)

for col in cols:
coords[(i, col)] = n
num = ""
cols = []
else:
if num != "":
n = Number(int(num), i, cols)

for col in cols:
coords[(i, col)] = n
num = ""
cols = []
if num != "":
n = Number(int(num), i, cols)
for col in cols:
coords[(i, col)] = n
num = ""
cols = []

cum = 0
for part in parts:
possible_nums = set()
for valid_coord in part.valid_coodinates():
if valid_coord in coords:
possible_nums.add(coords[valid_coord])
if len(possible_nums) == 2:
part1, part2 = tuple(possible_nums)
cum += part1.value * part2.value

return cum
Loading

0 comments on commit cbf61e4

Please sign in to comment.