Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pathlib import Path
- def parse(line):
- direction, amount = line.split(" ")
- return direction.lower(), int(amount)
- offsets = {"u": (0, 1), "d": (0, -1), "l": (-1, 0), "r": (1, 0)}
- class Coord:
- x, y = 0, 0
- def __init__(self, x=0, y=0):
- self.x, self.y = x, y
- def move(self, tx, ty):
- self.x += tx
- self.y += ty
- def carry(self, other):
- if abs(self.x - other.x) > 0:
- other.x += (1 if self.x > other.x else -1)
- if abs(self.y - other.y) > 0:
- other.y += (1 if self.y > other.y else -1)
- return Coord(other.x, other.y)
- def distance(self, other):
- return max(abs(self.x - other.x), abs(self.y - other.y))
- class Rope:
- head = Coord(0,0)
- knots = []
- visited = {(0,0)}
- def __init__(self, knots=2):
- # head is a knot
- for n in range(knots-1):
- self.knots.append(Coord(0,0))
- def move(self, direction, amount):
- for _ in range(amount):
- self.head.move(*offsets[direction])
- # each knot "carries" the next one
- current = self.head
- for knot in self.knots:
- while current.distance(knot) > 1:
- current.carry(knot)
- current = knot
- tail = self.knots[-1]
- self.visited.add((tail.x, tail.y))
- if __name__ == '__main__':
- data = Path("input.txt").read_text().splitlines()
- rope = Rope(knots=10)
- for line in data:
- direction, amount = parse(line)
- rope.move(direction, amount)
- print(f"visited: {len(rope.visited)}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement