Created
December 9, 2022 23:45
-
-
Save bigntallmike/ca3ed6df1bed312ce31e9e3a5ad199cc to your computer and use it in GitHub Desktop.
Advent of Code 2022 Day 9 Python -- no optimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import sys | |
class location: | |
def __init__(self, x, y): | |
self.x = x | |
self.y = y | |
def deltax(self, other): | |
return abs(other.x - self.x) | |
def deltay(self, other): | |
return abs(other.y - self.y) | |
def diagonal(self, other): | |
if ( | |
(self.deltax(other) > 1 or self.deltay(other) > 1) | |
and self.x != other.x | |
and self.y != other.y | |
): | |
return True | |
def day9b(moves): | |
# H = T[0] | |
T = [] | |
for i in range(10): | |
T.append(location(1, 1)) | |
T_positions = [(1, 1)] | |
for direction, quantity in (_.split() for _ in moves): | |
print(f"DEBUG: {direction} {quantity}") | |
for move in range(int(quantity)): | |
if direction == "R": | |
print("Head moving right one") | |
T[0].x += 1 | |
elif direction == "L": | |
print("Head moving left one") | |
T[0].x -= 1 | |
elif direction == "U": | |
print("Head moving up one") | |
T[0].y += 1 | |
elif direction == "D": | |
print("Head moving down one") | |
T[0].y -= 1 | |
else: | |
print("Invalid direction") | |
sys.exit(1) | |
print(f"Head: {T[0].x}, {T[0].y}") | |
# Decide if tail moves and how: | |
for seg in range(1, 10): | |
if T[seg - 1].diagonal(T[seg]): | |
print(f"Tail {seg} moving diagonally") | |
if T[seg].x < T[seg - 1].x: | |
T[seg].x += 1 | |
else: | |
T[seg].x -= 1 | |
if T[seg].y < T[seg - 1].y: | |
T[seg].y += 1 | |
else: | |
T[seg].y -= 1 | |
elif T[seg - 1].deltax(T[seg]) > 1: | |
print(f"Tail {seg} moving horizontally") | |
if T[seg].x < T[seg - 1].x: | |
T[seg].x += 1 | |
else: | |
T[seg].x -= 1 | |
elif T[seg - 1].deltay(T[seg]) > 1: | |
print(f"Tail {seg} moving vertically") | |
if T[seg].y < T[seg - 1].y: | |
T[seg].y += 1 | |
else: | |
T[seg].y -= 1 | |
T_positions.append((T[9].x, T[9].y)) | |
print(f"Tail 9: {T[9].x}, {T[9].y}") | |
return T_positions | |
if __name__ == "__main__": | |
from day9moves import moves | |
moves = moves.splitlines() | |
positions = set(day9b(moves)) | |
print(positions) | |
print(len(positions)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment