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-1.py 2.4KB

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