You're already almost 1.5km (almost a mile) below the surface of the ocean, already so deep that you can't see any sunlight. What you can see, however, is a giant squid that has attached itself to the outside of your submarine.
Maybe it wants to play bingo?
Bingo is played on a set of boards each consisting of a 5x5 grid of numbers. Numbers are chosen at random, and the chosen number is marked on all boards on which it appears. (Numbers may not appear on all boards.) If all numbers in any row or any column of a board are marked, that board wins. (Diagonals don't count.)
The submarine has a bingo subsystem to help passengers (currently, you and the giant squid) pass the time. It automatically generates a random order in which to draw numbers and a random set of boards (your puzzle input). For example:
7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
22 13 17 11 0
8 2 23 4 24
21 9 14 16 7
6 10 3 18 5
1 12 20 15 19
3 15 0 2 22
9 18 13 17 5
19 8 7 25 23
20 11 10 24 4
14 21 16 12 6
14 21 17 24 4
10 16 15 9 19
18 8 23 26 20
22 11 13 6 5
2 0 12 3 7
After the first five numbers are drawn (7, 4, 9, 5, and 11), there are no winners, but the boards are marked as follows (shown here adjacent to each other to save space):
22 13 17 11 0 3 15 0 2 22 14 21 17 24 4
8 2 23 4 24 9 18 13 17 5 10 16 15 9 19
21 9 14 16 7 19 8 7 25 23 18 8 23 26 20
6 10 3 18 5 20 11 10 24 4 22 11 13 6 5
1 12 20 15 19 14 21 16 12 6 2 0 12 3 7
After the next six numbers are drawn (17, 23, 2, 0, 14, and 21), there are still no winners:
22 13 17 11 0 3 15 0 2 22 14 21 17 24 4
8 2 23 4 24 9 18 13 17 5 10 16 15 9 19
21 9 14 16 7 19 8 7 25 23 18 8 23 26 20
6 10 3 18 5 20 11 10 24 4 22 11 13 6 5
1 12 20 15 19 14 21 16 12 6 2 0 12 3 7
Finally, 24 is drawn:
22 13 17 11 0 3 15 0 2 22 14 21 17 24 4
8 2 23 4 24 9 18 13 17 5 10 16 15 9 19
21 9 14 16 7 19 8 7 25 23 18 8 23 26 20
6 10 3 18 5 20 11 10 24 4 22 11 13 6 5
1 12 20 15 19 14 21 16 12 6 2 0 12 3 7
At this point, the third board wins because it has at least one complete row or column of marked numbers (in this case, the entire top row is marked: 14 21 17 24 4).
The score of the winning board can now be calculated. Start by finding the sum of all unmarked numbers on that board; in this case, the sum is 188. Then, multiply that sum by the number that was just called when the board won, 24, to get the final score, 188 * 24 = 4512.
To guarantee victory against the giant squid, figure out which board will win first. What will your final score be if you choose that board?
# Python imports
from pathlib import Path
from typing import Iterable, List, Tuple
import numpy as np
# Paths to data
testpath = Path("day04_test.txt")
datapath = Path("day04_data.txt")
def load_input(fpath: Path) -> Tuple[List[int], List[np.array]]:
"""Return a tuple of bingo calls and boards
:param fpath: Path to data file
"""
boards = []
with fpath.open("r") as ifh:
lines = ifh.readlines()
# Bingo calls
calls = [int(_) for _ in lines[0].split(",")]
# Boards
board = []
for line in [_.strip().split() for _ in lines[1:]]:
if len(line) == 0:
if len(board):
boards.append(np.array(board))
board = []
else:
board.append([int(_) for _ in line])
return calls, boards
It seems easiest to implement the mechanism described in the puzzle text, using numpy
arrays for boards, so we can use the array methods to make our lives easier. Specifically, we can test the board (and retain its shape) against a list of called numbers with np.isin()
to generate a mask of marked/unmarked numbers. Then we can operate on the mask to test for winning boards.
Once we have a winning board, we can use the mask to exclude marked values, and calculate the sum of unmarked values quickly.
def check_rows(mask: np.array) -> bool:
"""Return True if any row is all True
:param mask: numpy array mask
"""
for row in mask:
if row.all():
return True
return False
def check_cols(mask: np.array) -> bool:
"""Return True if any column is all True
:param mask: numpy array mask
"""
for row in mask.T:
if row.all():
return True
return False
def score_board(board: np.array, mask: np.array) -> int:
"""Return the sum of the unmarked values in the board
:param board: bingo board
:param mask: mask of marked (True) numbers in bingo board
"""
# Take inverse of mask so that False now indicates marked
# values, for taking the sum of unmarked values
return sum(board[~mask])
def win_bingo(calls: List[int], boards: List[np.array]) -> int:
"""Return the score of the winning board
:param calls: list of bingo calls
:param boards: list of bingo boards
"""
# Iterate over bingo calls
for idx in range(len(calls)):
called = calls[:idx+1] # numbers called, so far
# Check boards for a winner
for board in boards:
# mask values as True if number called
mask = np.isin(board, called)
# If a row or column is complete, we have a winner
if check_rows(mask) or check_cols(mask):
print(f"winner!\n{board}")
return called[-1] * score_board(board, mask)
With the test data:
calls, boards = load_input(testpath)
win_bingo(calls, boards)
winner! [[14 21 17 24 4] [10 16 15 9 19] [18 8 23 26 20] [22 11 13 6 5] [ 2 0 12 3 7]]
4512
And solving the puzzle:
calls, boards = load_input(datapath)
win_bingo(calls, boards)
winner! [[80 16 10 79 55] [93 60 4 0 29] [ 7 97 3 9 86] [43 67 78 64 35] [44 83 40 33 12]]
51776
On the other hand, it might be wise to try a different strategy: let the giant squid win.
You aren't sure how many bingo boards a giant squid could play at once, so rather than waste time counting its arms, the safe thing to do is to figure out which board will win last and choose that one. That way, no matter which boards it picks, it will win for sure.
In the above example, the second board is the last to win, which happens after 13 is eventually called and its middle column is completely marked. If you were to keep playing until this point, the second board would have a sum of unmarked numbers equal to 148 for a final score of 148 * 13 = 1924.
Figure out which board will win last. Once it wins, what would its final score be?
To implement this tweak in the strategy, we update the list of boards when checking after every called number. We only keep boards where there is not a winning row or column, until we reach the last board. For the last board, we check as before, when we wanted to find a winning board.
def lose_bingo(calls: List[int], boards: List[np.array]) -> int:
"""Return score of losing board
:param calls: list of bingo calls
:param boards: list of bingo boards
"""
# Iterate over bingo calls
for idx in range(len(calls)):
called = calls[:idx+1]
# Check boards for winners. Obtain a list of boards that have not
# won yet (newboards), until we reach the last board
newboards = []
# Iterate over the current set of boards
for board in boards:
# mask values True if number called
mask = np.isin(board, called)
# if the board is not a winner, append it to newboards
if not(check_rows(mask) or check_cols(mask)):
newboards.append(board)
elif len(boards) == 1: # but if it is, and it's the last one...
print(f"loser!\n{board}")
return called[-1] * score_board(board, mask)
# Continue only with list of boards that have not won, yet
boards = newboards[:]
For the test data:
calls, boards = load_input(testpath)
lose_bingo(calls, boards)
loser! [[ 3 15 0 2 22] [ 9 18 13 17 5] [19 8 7 25 23] [20 11 10 24 4] [14 21 16 12 6]]
1924
And for the puzzle:
calls, boards = load_input(datapath)
lose_bingo(calls, boards)
loser! [[ 6 3 41 5 44] [91 21 32 49 81] [29 85 47 20 14] [99 31 43 22 69] [90 4 45 8 16]]
16830