From 6e42e7ecd348f554db43890d762cbbdd167cdd0a Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Tue, 15 Dec 2015 13:22:32 +0100 Subject: [PATCH] Solution to day 15, now in python 3. --- day-15/input.txt | 4 ++++ day-15/solution.py | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 day-15/input.txt create mode 100644 day-15/solution.py diff --git a/day-15/input.txt b/day-15/input.txt new file mode 100644 index 0000000..d1af06e --- /dev/null +++ b/day-15/input.txt @@ -0,0 +1,4 @@ +Sugar: capacity 3, durability 0, flavor 0, texture -3, calories 2 +Sprinkles: capacity -3, durability 3, flavor 0, texture 0, calories 9 +Candy: capacity -1, durability 0, flavor 4, texture 0, calories 1 +Chocolate: capacity 0, durability 0, flavor -2, texture 2, calories 8 diff --git a/day-15/solution.py b/day-15/solution.py new file mode 100644 index 0000000..cdf95e6 --- /dev/null +++ b/day-15/solution.py @@ -0,0 +1,47 @@ +from __future__ import print_function +import fileinput +import re +from operator import mul +from functools import reduce + +pattern = re.compile(r"(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)") + +ingredients = [] +calories = [] + +def computeScore(amounts): + scores = [sum(ingredients[idx][x] * value for idx, value in enumerate(amounts)) for x in range(4)] + + return reduce(mul, [max(x, 0) for x in scores], 1) + +def computeCalories(amounts): + return sum(a * b for a, b in zip(calories, amounts)) + + +def computeMax(ingredient, budget, currentAmounts): + budgetLeft = budget - sum(currentAmounts[:ingredient]) + + if ingredient == len(ingredients) - 1: + currentAmounts[ingredient] = budgetLeft + score = computeScore(currentAmounts) + if computeCalories(currentAmounts) == 500: + return score, score + + return score, None + + results = [] + resultsCorrect = [0] + for n in range(budgetLeft + 1): + currentAmounts[ingredient] = n + general, correct = computeMax(ingredient + 1, budget, currentAmounts) + results.append(general) + resultsCorrect.append(correct) + + return max(results), max(x for x in resultsCorrect if x is not None) + +for line in fileinput.input(): + match = pattern.match(line) + ingredients.append([int(x) for x in match.group(2, 3, 4, 5)]) + calories.append(int(match.group(6))) + +print(computeMax(0, 100, [0] * len(ingredients)))