Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
2.5 kB
3
Indexable
Never
with open('04.in', 'r') as file:
    data = (line.rstrip() for line in file)
    data = list(line for line in data if line)

numbersraw = data.pop(0)
numbers = numbersraw.split(",")

boards = []

while True:   # this loop parses the input and creates a list of boards
    board = []
    for y in range(5):
        board.append(data.pop(0).split())
    boards.append(board)
    if not data:
        break

boards_to_ignore = []
bingoboards = []
lastnumber = ""

def checkbingo(board, number, bingoboards):   # function to check a board to see if there's a bingo
    global lastnumber
    for i in range(5):   # check rows
        bingo = True
        for j in range(5):
            if board[i][j] != 'x':
                bingo = False
        if bingo:
            bingoboards.append(board)
            lastnumber = number
            # calcvalue(board, number) # uncomment for part one solution

    for i in range(5):   # check columns
        bingo = True
        for j in range(5):
            if board[j][i] != 'x':
                bingo = False
        if bingo:
            bingoboards.append(board)
            lastnumber = number
            # calcvalue(board, number) # uncomment for part one solution

    return bingoboards

def calcvalue(board, number):   # function to calculate value for matching board
    print(board, number)
    total = 0
    for row in board:
        for item in row:
            if item.isdigit():
                total += int(item)
    total *= int(number)
    print(total)
    quit()



for number in numbers:   # main loop
    print(number)
    for b, board in enumerate(boards):
        if b in boards_to_ignore:   # if this board's index is already in the matched list, skip it
            continue
        for y, row in enumerate(board):
            for x, item in enumerate(row):
                if item == str(number):
                    boards[b][y][x] = 'x'
                    bingolen = len(bingoboards)     # see how many matching boards there are now... 
                    bingoboards = checkbingo(board, number, bingoboards)   # ...check the current board for a bingo...
                    if len(bingoboards) > bingolen:   # if the matched boards list is bigger now, there must have been a bingo
                        boards_to_ignore.append(b)   # so we can add this board to the bingo list

calcvalue(bingoboards[-1], lastnumber)