Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

aoc4-1.py 2.5KB

3 år sedan
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. for i, board in enumerate(boards):
  63. board.mark(el)
  64. if board.check():
  65. return (board, int(el) * board.sum_unmarked())
  66. if __name__ == "__main__":
  67. board, total = main()
  68. print(board)
  69. print(total)