From 13ef0112e289215ac7ecd94da128b0c3e001be64 Mon Sep 17 00:00:00 2001 From: Dylan Sheehy Date: Sun, 5 Dec 2021 12:51:56 -0600 Subject: [PATCH] modified day 4 and .gitignore --- 2021/day04a.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2021/day04b.py | 17 +++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/2021/day04a.py b/2021/day04a.py index e69de29..b6a9e03 100644 --- a/2021/day04a.py +++ b/2021/day04a.py @@ -0,0 +1,44 @@ +class Bingo: + def __init__(self, board): + self.board = [[int(n) for n in row.split()] for row in board.split("\n")] + self.skip = False + + def winner(self): + for row in self.board: + if all(n == -1 for n in row): + self.skip = True + return True + for i in range(5): + column = [self.board[j][i] for j in range(5)] + if all(n == -1 for n in column): + self.skip = True + return True + return False + + def draw(self, n): + for r, row in enumerate(self.board): + for c, num in enumerate(row): + if num == n: + self.board[r][c] = -1 + + def unmarked_sum(self): + ans = 0 + for row in self.board: + ans += sum(x for x in row if x != -1) + return ans + + +f = open('input04.txt') +numbers = map(int, next(f).strip().split(',')) +next(f) +boards = [Bingo(b) for b in f.read().strip().split("\n\n")] + +def main(): + for n in numbers: + for b in boards: + b.draw(n) + if b.winner(): + return b.unmarked_sum() * n + +if __name__ == '__main__': + print(main()) \ No newline at end of file diff --git a/2021/day04b.py b/2021/day04b.py index e69de29..7683cef 100644 --- a/2021/day04b.py +++ b/2021/day04b.py @@ -0,0 +1,17 @@ +from day04a import numbers, boards + +def main(): + last_score = 0 + for n in numbers: + for b in boards: + # skip if the Bingo board already won + if b.skip: + continue + b.draw(n) + if b.winner(): + last_score = n * b.unmarked_sum() + print(last_score) + return last_score + +if __name__ == '__main__': + print(main()) \ No newline at end of file