Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def read_file(filename):
- with open(f"{filename}", "r") as infile:
- output = infile.read().splitlines()
- return output
- class Location:
- def __init__(self, x, y):
- self.x = x
- self.y = y
- @property
- def location(self):
- return (self.x, self.y)
- def move(self, direction, number=1):
- if direction.upper() == "L":
- self.move_left()
- elif direction.upper() == "R":
- self.move_right()
- elif direction.upper() == "U":
- self.move_up()
- elif direction.upper() == "D":
- self.move_down()
- else:
- raise ValueError
- def move_left(self):
- self.x = self.x - 1
- def move_right(self):
- self.x = self.x + 1
- def move_up(self):
- self.y = self.y + 1
- def move_down(self):
- self.y = self.y - 1
- def main(knots_to_track):
- lines = read_file("inputs/9.csv")
- knots = []
- for i in range(knots_to_track):
- knots.append(Location(0,0))
- tail_locations = [knots[-1:][0].location]
- for line in lines:
- direction_to_move = line.split(" ")[0]
- spaces_to_move = int(line.split(" ")[1])
- for i in range(spaces_to_move):
- knots[0].move(direction_to_move)
- for j in range(1,len(knots)):
- delta = Location(knots[j-1].x - knots[j].x, knots[j-1].y - knots[j].y)
- if abs(delta.x) <= 1 and abs(delta.y) <= 1:
- pass
- else:
- if delta.location == (2,0):
- knots[j].move_right()
- elif delta.location == (-2,0):
- knots[j].move_left()
- elif delta.location == (0,2):
- knots[j].move_up()
- elif delta.location == (0,-2):
- knots[j].move_down()
- elif delta.x > 0 and delta.y > 0:
- knots[j].move_right()
- knots[j].move_up()
- elif delta.x > 0 and delta.y < 0:
- knots[j].move_right()
- knots[j].move_down()
- elif delta.x < 0 and delta.y > 0:
- knots[j].move_left()
- knots[j].move_up()
- elif delta.x < 0 and delta.y < 0:
- knots[j].move_left()
- knots[j].move_down()
- tail_locations.append(knots[-1:][0].location)
- print(len(set(tail_locations)))
- if __name__ == "__main__":
- main(2)
- main(10)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement