summary refs log tree commit diff stats
path: root/day4.py
blob: 6cf430ca733938ef5e38d2d31007b120e15873b6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python

import numpy as np

def bingo(board):
    for i in range(5):
        if np.all(board[:, i] == 1) or np.all(board[i, :] == 1):
            return True
    return False

def any_bingo(boards):
    for index, board in enumerate(boards):
        if bingo(board):
            yield index
    yield -1

with open("day4.txt") as data:
    order = next(data).strip().split(',')
    next(data)
    boards = []
    current_board = []
    for line in data:
        if line == '\n':
            boards.append(current_board)
            current_board = []
        else:
            current_board.append(line.strip().split())
    boards = np.array(boards).astype(int)
    print(boards.shape)
    marked = np.zeros_like(boards)
    # part 1
    for num in map(int, order):
        indices = np.where(boards == num)
        marked[indices] = 1
        if (board_num := next(any_bingo(marked))) != -1:
            ind = np.where(marked[board_num] == 0)
            total = np.sum(boards[board_num][ind])
            print(total * num)
            break
    # part 2
    marked[:] = 0
    won = None
    for num in map(int, order):
        indices = np.where(boards == num)
        marked[indices] = 1
        nextwon = {index for index in any_bingo(marked) if index != -1}
        if len(nextwon) == 99:
            diff = (nextwon - won).pop()
            print(diff)
            ind = np.where(marked[diff] == 0)
            total = np.sum(boards[diff][ind])
            print(total*num)
            break
        else:
            won = nextwon