Browse Source

Adding day 02 (probably will rewrite in a bit)

pull/2/head
Ryan Reed 3 years ago
parent
commit
c5f6c8be26
4 changed files with 1099 additions and 0 deletions
  1. +6
    -0
      inputs/day02-example1.txt
  2. +1000
    -0
      inputs/day02.txt
  3. +61
    -0
      puzzles/day02.py
  4. +32
    -0
      puzzles/test_day02.py

+ 6
- 0
inputs/day02-example1.txt View File

@ -0,0 +1,6 @@
forward 5
down 5
forward 8
up 3
down 8
forward 2

+ 1000
- 0
inputs/day02.txt
File diff suppressed because it is too large
View File


+ 61
- 0
puzzles/day02.py View File

@ -0,0 +1,61 @@
"""
Advent of Code 2021 - Day 02
Run with:
python puzzles/day02.py inputs/day02.txt
"""
import pathlib
import sys
from typing import List, Tuple
def part1(inputs: List[int], horizontal: int=0, depth: int=0) -> int:
for line in inputs:
step = line.split()
if step[0] == "forward":
horizontal += int(step[1])
elif step[0] == "up":
depth -= int(step[1])
elif step[0] == "down":
depth += int(step[1])
return horizontal * depth
def part2(inputs: List[int], horizontal: int=0, depth: int=0, aim: int=0) -> int:
for line in inputs:
step = line.split()
if step[0] == "forward":
horizontal += int(step[1])
depth += aim * int(step[1])
elif step[0] == "up":
aim -= int(step[1])
elif step[0] == "down":
aim += int(step[1])
return horizontal * depth
def parse(inputs: str) -> List[List[str]]:
"""Parse the input string"""
return inputs.split("\n")
def solve(path: str) -> Tuple[int, int]:
"""Solve the puzzle"""
puzzle_input = parse(pathlib.Path(path).read_text().strip())
part1_result = part1(puzzle_input)
part2_result = part2(puzzle_input)
return part1_result, part2_result
def main() -> None:
for path in sys.argv[1:]:
print(f"Input File: {path}")
part1_result, part2_result = solve(path)
print(f"Part 1 Result: {part1_result}")
print(f"Part 2 Result: {part2_result}")
if __name__ == "__main__":
main()

+ 32
- 0
puzzles/test_day02.py View File

@ -0,0 +1,32 @@
import pathlib
import pytest
import day02 as aoc
INPUTS_DIR = f"{pathlib.Path(__file__).parent.parent}/inputs"
@pytest.fixture
def example_data():
input_path = f"{INPUTS_DIR}/day02-example1.txt"
return aoc.parse(pathlib.Path(input_path).read_text().strip())
@pytest.fixture
def day02_data():
input_path = f"{INPUTS_DIR}/day02.txt"
return aoc.parse(pathlib.Path(input_path).read_text().strip())
def test_example1(example_data):
assert aoc.part1(example_data) == 150
def test_example2(example_data):
assert aoc.part2(example_data) == 900
def test_part1(day02_data):
assert aoc.part1(day02_data) == 1670340
def test_part2(day02_data):
assert aoc.part2(day02_data) == 1954293920

Loading…
Cancel
Save