From 75371082a4396803d49e6754d537b0b567df6971 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Sat, 4 Dec 2021 12:04:49 +0100 Subject: [PATCH] 2021 day4/python: add solution --- 2021/day4/day4.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100755 2021/day4/day4.py diff --git a/2021/day4/day4.py b/2021/day4/day4.py new file mode 100755 index 0000000..695fc89 --- /dev/null +++ b/2021/day4/day4.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python + +import time + +import sys + +def board_won(board): + for row in board: + if all(x is None for x in row): + return True + for i in range(len(board[0])): + if all(row[i] is None for row in board): + return True + return False + +if __name__ == '__main__': + lines = [line.strip() for line in sys.stdin.readlines()] + + draws = [int(n) for n in lines[0].split(',')] + + boards = [] + for i in range(2, len(lines), 6): + boards.append([[int(n) for n in line.split()] for line in lines[i:i+5]]) + + wins = [] + for draw in draws: + for board_idx, board in enumerate(boards): + if board is None: + continue + for row in board: + try: + idx = row.index(draw) + row[idx] = None + except ValueError: + pass + if board_won(board): + wins.append(draw * sum(n for row in board for n in row if n is not None)) + boards[board_idx] = None + + print(wins[0]) + print(wins[-1])