You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

aoc4-2.py 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. class Board:
  2. def __init__(self, lines, boardsize=None, boardnum=None):
  3. self.lines = [[el for el in line.split(" ") if el != ""] for line in lines]
  4. self.boardsize = 5 if boardsize == None else boardsize
  5. self.boardnum = 0 if boardnum == None else boardnum
  6. self.marks = []
  7. for _ in range(self.boardsize):
  8. self.marks.append([0]*self.boardsize)
  9. def mark(self, digit):
  10. import pdb
  11. # if self.boardnum == 1:
  12. # pdb.set_trace()
  13. for i, line in enumerate(self.lines):
  14. if digit in line:
  15. y = i
  16. x = line.index(digit)
  17. self.marks[y][x] = 1
  18. return None
  19. def check(self):
  20. for line in self.marks:
  21. if sum(line) == 5:
  22. return True
  23. for i in range(5):
  24. if self.marks[0][i] == 1 and \
  25. self.marks[1][i] == 1 and \
  26. self.marks[2][i] == 1 and \
  27. self.marks[3][i] == 1 and \
  28. self.marks[4][i] == 1:
  29. return True
  30. return False
  31. def sum_unmarked(self):
  32. total = 0
  33. for i in range(self.boardsize):
  34. for j in range(self.boardsize):
  35. if self.marks[j][i] == 0:
  36. total += int(self.lines[j][i])
  37. return total
  38. def __repr__(self):
  39. outstr = f"Board {self.boardnum}:\n"
  40. for i in range(self.boardsize):
  41. outstr += f"{' '.join([str(el).rjust(2) for el in self.lines[i]])} {' '.join([str(el).rjust(2) for el in self.marks[i]])}\n"
  42. return outstr
  43. def __str__(self):
  44. outstr = f"Board {self.boardnum}:\n"
  45. for i in range(self.boardsize):
  46. outstr += f"{' '.join([str(el).rjust(2) for el in self.lines[i]])} {' '.join([str(el).rjust(2) for el in self.marks[i]])}\n"
  47. return outstr
  48. def main():
  49. with open("aoc4-1.txt", "r") as file:
  50. lines = [line.strip() for line in file.readlines()]
  51. firstline = lines[0].split(",")
  52. lines = lines[2:]
  53. i = 0
  54. j = 0
  55. boards = []
  56. while i < len(lines):
  57. boards.append(Board(lines[i:i+5], boardnum=j))
  58. j += 1
  59. i += 6
  60. for el in firstline:
  61. print(el)
  62. is_to_pop = []
  63. for i, board in enumerate(boards):
  64. board.mark(el)
  65. if board.check():
  66. if len(boards) > 1:
  67. is_to_pop.append(i)
  68. else:
  69. return (board, int(el) * board.sum_unmarked())
  70. boards = [board for i, board in enumerate(boards) if i not in is_to_pop]
  71. if __name__ == "__main__":
  72. board, total = main()
  73. print(board)
  74. print(total)