您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

aoc5-1.py 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import pdb
  2. class FloorMap:
  3. def __init__(self, size_x, size_y):
  4. self.board = []
  5. for _ in range(size_y+1):
  6. self.board.append([0]*(size_x+1))
  7. def add_line(self, start_pos, end_pos):
  8. if start_pos[0] == end_pos[0]:
  9. if start_pos[1] > end_pos[1]:
  10. start_pos, end_pos = end_pos, start_pos
  11. for i in range(start_pos[1], end_pos[1]+1):
  12. self.board[i][start_pos[0]] = self.board[i][start_pos[0]] + 1
  13. else:
  14. if start_pos[0] > end_pos[0]:
  15. start_pos, end_pos = end_pos, start_pos
  16. for i in range(start_pos[0], end_pos[0]+1):
  17. self.board[start_pos[1]][i] = self.board[start_pos[1]][i] + 1
  18. def count_inters(self):
  19. return sum([len([el for el in line if el >= 2]) for line in self.board])
  20. def __repr__(self):
  21. outstr = ""
  22. for line_num in range(10):
  23. outstr += f"{' '.join(str(self.board[line_num]))}"
  24. return outstr
  25. def __str__(self):
  26. outstr = ""
  27. for line_num in range(10):
  28. outstr += f"{' '.join(str(self.board[line_num]))}"
  29. return outstr
  30. def main():
  31. with open("aoc5-1.txt", "r") as file:
  32. lines = [line.strip() for line in file.readlines()]
  33. # Each line is a pair of x,y coordinates...es separated by " -> "
  34. lines = [[list(map(int, el.split(","))) for el in line.split(" -> ")] for line in lines]
  35. # For 5-1, only care about the ones where, of x1,y1 -> x2,y2, x1 == x2 or y1 == y2
  36. # i.e. only horizontal or vertical
  37. lines = [line for line in lines if line[0][0] == line[1][0] or line[0][1] == line[1][1]]
  38. # god, this feels goofy
  39. size_x = max([max(line[0][0], line[1][0]) for line in lines])
  40. size_y = max([max(line[0][1], line[1][1]) for line in lines])
  41. board_map = FloorMap(size_x, size_y)
  42. for line in lines:
  43. board_map.add_line(*line)
  44. print(board_map.count_inters())
  45. if __name__ == "__main__":
  46. main()