Solution to problem 3 part 1 in Python

This commit is contained in:
David Doblas Jiménez 2022-02-28 12:36:27 +01:00
parent 3e9e31255c
commit d8be81fb92

62
src/Year_2015/P3.py Normal file
View File

@ -0,0 +1,62 @@
# --- Day 3: Perfectly Spherical Houses in a Vacuum ---
# Santa is delivering presents to an infinite two-dimensional grid of houses.
# He begins by delivering a present to the house at his starting location, and
# then an elf at the North Pole calls him via radio and tells him where to move
# next. Moves are always exactly one house to the north (^), south (v), east
# (>), or west (<). After each move, he delivers another present to the house
# at his new location.
# However, the elf back at the north pole has had a little too much eggnog, and
# so his directions are a little off, and Santa ends up visiting some houses
# more than once. How many houses receive at least one present?
# For example:
# > delivers presents to 2 houses: one at the starting location, and one to
# the east.
# ^>v< delivers presents to 4 houses in a square, including twice to the
# house at his starting/ending location.
# ^v^v^v^v^v delivers a bunch of presents to some very lucky children at
# only 2 houses.
from typing import Tuple
with open("files/P3.txt") as f:
moves = [line for line in f.read().strip().split()][0]
def move_up(pos: Tuple[int, int]) -> Tuple[int, int]:
return pos[0], pos[1] + 1
def move_down(pos: Tuple[int, int]) -> Tuple[int, int]:
return pos[0], pos[1] - 1
def move_left(pos: Tuple[int, int]) -> Tuple[int, int]:
return pos[0] - 1, pos[1]
def move_right(pos: Tuple[int, int]) -> Tuple[int, int]:
return pos[0] + 1, pos[1]
def part_1() -> None:
pos = [(0, 0)]
for move in moves:
if move == "^":
pos.append(move_up(pos[-1]))
elif move == "v":
pos.append(move_down(pos[-1]))
elif move == "<":
pos.append(move_left(pos[-1]))
elif move == ">":
pos.append(move_right(pos[-1]))
print(f"{len(set(pos))} houses receive at least one present")
if __name__ == "__main__":
part_1()