74 lines
1.8 KiB
Python

from json import dumps
from time import sleep
# Input parsing - part 1 and 2
def getInput(inputfile="input.in"):
inp = []
with open(inputfile, "r") as f:
for line in f:
inp.append(line.strip())
return inp
def parseInput(inputfile="input.in"):
parsed = {}
inp = getInput(inputfile=inputfile)
counter = 0
for i in inp:
card, values = i.split(":")
values = values.strip().split("|")
parsed[counter] = {}
parsed[counter]["winning"] = [x for x in values[0].split(" ") if x != ""]
parsed[counter]["numbers"] = [x for x in values[1].split(" ") if x != ""]
parsed[counter]["to_win"] = len([x for x in parsed[counter]["numbers"] if x in parsed[counter]["winning"]])
parsed[counter]["times"] = 1
counter += 1
return parsed
# Winning amount for part 1
def winningAmount(card):
amount = 0
looked_through = []
for num in card["numbers"]:
if num in card["winning"] and num not in looked_through:
if not amount:
amount = 1
else:
amount *= 2
looked_through.append(num)
return amount
cards_won = 0
def cardTree(cards:dict, move:int) -> int:
# For each winning card:
# 1. We move until we've reached the card we're moving towards or until no more to win
# 2. Do the same for each card we moved into
# 3. Recurse until we've reached the end
card = cards[move]
global cards_won
cards_won += 1
if card["to_win"] == 0:
return
s = 0
for i in range(1, card["to_win"]+1):
cardTree(cards, move + i)
return
def main():
s = 0
cards = parseInput(inputfile="input.in")
cnt = 0
# Part 1
for card in cards:
w = winningAmount(cards[card])
x = cardTree(cards, cnt)
s += w
cnt += 1
print(f"First part: {s}")
print(f"Second part: {cards_won}")
if __name__ == "__main__":
main()