Skip to content

Instantly share code, notes, and snippets.

@albertein
Created December 8, 2021 03:34
Show Gist options
  • Save albertein/954c45c3fad3c927c77ff9f394656dc0 to your computer and use it in GitHub Desktop.
Save albertein/954c45c3fad3c927c77ff9f394656dc0 to your computer and use it in GitHub Desktop.
BINGO_SIZE = 5
class Bingo:
def __init__(self):
self.column_count = [0] * BINGO_SIZE
self.row_count = [0] * BINGO_SIZE
self.data = []
self.index = {}
self.called = set()
def add_row(self, numbers):
row_idx = len(self.data)
for idx, number in enumerate(numbers):
self.index[number] = (row_idx, idx)
self.data.append(numbers)
def maybe_bingo(self, number):
if not number in self.index:
return False
self.called.add(number)
row, column = self.index[number]
self.row_count[row] += 1
self.column_count[column] += 1
print(self.row_count, self.column_count)
if self.row_count[row] == BINGO_SIZE or self.column_count[column] == BINGO_SIZE:
return True
def score(self):
total = 0
for number in self.index:
if not number in self.called:
total += int(number)
return total
def find_winner_loser(draws, bingo_cards):
won_cards = set()
first_score = None
already_won = 0
for draw in draws:
for card in bingo_cards:
if card in won_cards:
continue
if card.maybe_bingo(draw):
won_cards.add(card)
if not first_score:
first_score = int(draw) * card.score()
elif len(won_cards) == len(bingo_cards):
last_score = int(draw) * card.score()
return first_score, last_score
if __name__ == '__main__':
with open('input.txt') as data:
draws = data.readline().strip().split(',')
bingo_cards = []
current_card = None
while (line := data.readline()):
line = line.strip()
if not line:
current_card = Bingo()
bingo_cards.append(current_card)
continue
current_numbers = [number for number in line.split(' ') if number]
current_card.add_row(current_numbers)
print(find_winner_loser(draws, bingo_cards))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment