Advent-of-Code/2021/4/main2.py

84 lines
2.9 KiB
Python
Raw Normal View History

# all the numbers called, in order
numbers = []
temp_board = []
boards = []
fills = []
board_index = 0
####
def Victory(board):
for y in range(0, len(board)):
if(board[y] == [True, True, True, True, True]):
return True;
# NOTE(dev): Assumes all columns are the same length
for x in range(0, len(board[0])):
num_true = 0
for y in range(0, len(board)):
if(board[y][x]):
num_true = num_true + 1
if(num_true == len(board[0])):
return True
return False
####
def FindWinner(numbers):
indexes = []
winning_indexes = []
for i in range(0, len(boards)):
indexes.append(i)
for i in range(0, len(numbers)):
for board_index in range(0, len(boards)):
if(board_index not in winning_indexes):
for y in range(0, len(boards[board_index])):
for x in range(0, len(boards[board_index][y])):
if(boards[board_index][y][x] == numbers[i]):
fills[board_index][y][x] = True
if(Victory(fills[board_index])):
print('Victory with', numbers[i], 'on board', board_index, '!!')
winning_indexes.append(int(board_index))
indexes.remove(int(board_index))
if(len(indexes) == 0):
return numbers[i], board_index
#### MAIN EXECUTION ####
with open('data', 'r') as fp:
for i,line in enumerate(fp):
if(i == 0):
numbers = line.strip().split(',')
elif(len(line.strip()) == 0):
if(len(temp_board) > 0): # i.e. skip the first, empty one
# add in the next player board
boards.append(temp_board)
temp_board = []
# create a blank answer board for this player board
for j in range(0,5):
temp_board.append([False, False, False, False, False])
fills.append(temp_board);
temp_board = []
board_index = board_index + 1
else:
# add the next array of numbers to the temporary board object
temp_board.append(line.strip().split())
winning_number,winning_board_index = FindWinner(numbers)
print('Winning Number:', winning_number, ', Winning Board Index: ', winning_board_index)
total = 0
for y in range(0, len(fills[winning_board_index])):
for x in range(0, len(fills[winning_board_index][y])): # assumes size is same for all columns
if(not fills[winning_board_index][y][x]):
total = total + int(boards[winning_board_index][y][x])
print(total * int(winning_number))
# # DEBUG(dev): Show full contents of all boards
# for x in range(0, len(boards)):
# for y in range(0, len(boards[x])):
# for z in range(0, len(boards[x][y])):
# print(boards[x][y][z])