AdventOfCode/2016/01/solution.py

85 lines
2.5 KiB
Python

#!/bin/python3
import sys
from pprint import pprint
# Read instructions from file
with open("input", "r") as file:
instructions = file.read().strip().split(", ")
#########################################
# #
# Part 1 #
# #
#########################################
# Define directions and movements in terms of (x, y) vectors
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # North, East, South, West
# Starting position and direction
x, y = 0, 0
current_direction = 0 # Start facing North (index 0 in directions)
# Process each instruction
for instruction in instructions:
turn, steps = instruction[0], int(instruction[1:])
# Update direction based on the turn
if turn == 'R':
current_direction = (current_direction + 1) % 4 # Turn right
elif turn == 'L':
current_direction = (current_direction - 1) % 4 # Turn left
# Move in the current direction
dx, dy = directions[current_direction]
x += dx * steps
y += dy * steps
# Calculate Manhattan distance from the origin
distance = abs(x) + abs(y)
print(distance)
#########################################
# #
# Part 2 #
# #
#########################################
# Define directions and movements in terms of (x, y) vectors
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # North, East, South, West
# Starting position and direction
x, y = 0, 0
current_direction = 0 # Start facing North (index 0 in directions)
visited = set() # To track visited positions
visited.add((x, y)) # Starting point is visited
# Read instructions from file
with open("input", "r") as file:
instructions = file.read().strip().split(", ")
# Process each instruction
for instruction in instructions:
turn, steps = instruction[0], int(instruction[1:])
# Update direction based on the turn
if turn == 'R':
current_direction = (current_direction + 1) % 4 # Turn right
elif turn == 'L':
current_direction = (current_direction - 1) % 4 # Turn left
# Move step by step in the current direction
dx, dy = directions[current_direction]
for _ in range(steps):
x += dx
y += dy
if (x, y) in visited:
# Found the first location visited twice
distance = abs(x) + abs(y)
print(distance)
exit()
visited.add((x, y))