solution.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/python3
  2. import sys
  3. class Board:
  4. def __init__(self):
  5. self.matrix = []
  6. self.marks = []
  7. self.columns = 0
  8. self.winner = False
  9. self.last_draw = 0
  10. def __str__(self):
  11. return '\n'.join([ '\t'.join(str(e) for e in row) for row in self.matrix ])
  12. def decode(self, line):
  13. elements = ' '.join(line.split()).split(' ')
  14. self.columns = len(elements)
  15. self.matrix.append([ [int(e), False] for e in elements ])
  16. def mark(self, draw):
  17. self.last_draw = draw
  18. for row in self.matrix:
  19. for element in row:
  20. if draw == element[0]:
  21. element[1] = True
  22. def row_check(self, i):
  23. for j in range(self.columns):
  24. if not self.matrix[j][i][1]:
  25. return False
  26. return True
  27. def column_check(self, i):
  28. for j in range(self.columns):
  29. if not self.matrix[i][j][1]:
  30. return False
  31. return True
  32. def check_win(self):
  33. possible_wins = [ True for e in range(self.columns) ]
  34. for i in range(self.columns):
  35. horizontal = self.row_check(i)
  36. vertical = self.column_check(i)
  37. if (not horizontal) and (not vertical):
  38. possible_wins[i] = False
  39. continue
  40. for i in range(self.columns):
  41. if possible_wins[i]:
  42. self.winner = True
  43. def final_score(self):
  44. score = 0
  45. for row in self.matrix:
  46. for element in row:
  47. if not element[1]:
  48. score += element[0]
  49. return score * self.last_draw
  50. def someone_wins(draws, boards):
  51. for draw in draws:
  52. print('drawing', draw)
  53. # three passes, because there can be multiple winners
  54. for board in boards:
  55. board.mark(draw)
  56. for board in boards:
  57. board.check_win()
  58. for board in boards:
  59. if board.winner:
  60. return True
  61. return False
  62. draws = [ int(e) for e in input().split(',') ]
  63. boards = []
  64. for line in sys.stdin:
  65. if line == '\n':
  66. boards.append(Board())
  67. continue
  68. boards[-1].decode(line.rstrip('\n'))
  69. if someone_wins(draws, boards):
  70. for board in boards:
  71. if board.winner:
  72. print('board has won:\n', board)
  73. print('final score:', board.final_score())