summary refs log blame commit diff stats
path: root/day4.py
blob: 6cf430ca733938ef5e38d2d31007b120e15873b6 (plain) (tree)






















































                                                                       
#!/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
#n31'>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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134