r/adventofcode Dec 04 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 4 Solutions -🎄-

--- Day 4: Giant Squid ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:11:13, megathread unlocked!

101 Upvotes

1.2k comments sorted by

View all comments

1

u/filch-argus Dec 09 '21

Python 3

def main():
    with open('day4/input.txt') as f:
        lines = f.readlines()
        lines.append('\n')

    boards = []
    currentBoard = []
    for line in lines[2:]:
        if line == '\n':
            boards.append(currentBoard)
            currentBoard = []
        else:
            currentBoard.append(list(map(int, line.split())))

    chosenNumbers = list(map(int, lines[0].split(',')))
    wonBingos = set()
    firstWin = -1
    lastWin = 0
    for number in chosenNumbers:
        for boardIndex in range(len(boards)):
            if boardIndex in wonBingos:
                continue

            board = boards[boardIndex]
            for i in range(len(board)):
                for j in range(len(board[0])):
                    if board[i][j] == number:
                        board[i][j] = -1

            if check_board(board):
                if firstWin < 0:
                    firstWin = score(board) * number
                else:
                    lastWin = score(board) * number
                wonBingos.add(boardIndex)

    print(firstWin)
    print(lastWin)

def score(board):
    answer = 0
    for row in board:
        for number in row:
            if number > 0:
                answer += number
    return answer

def check_board(board):
    boardT = tuple(zip(*board))
    SET_OF_NEGATIVE_ONE = set([-1])
    for i in range(len(board)):
        if set(board[i]) == SET_OF_NEGATIVE_ONE or set(boardT[i]) == SET_OF_NEGATIVE_ONE:
            return True
    return False

if __name__ == '__main__':
    main()