November 09, 2023

Solution for Advent of Code 2015 - Day 15: Science for Hungry People

Link to the puzzle text

Part 1

This puzzle is a linear optimization. We are asked to take a total of 100 units of different ingredients, such that a linear combination of their attributes is maximized. Since both number of ingredients and total number of units are small, I used a brute force search. Three nested loops iterate over the number of ingredients 1, 2 and 3, while the weight of ingredient 4 is the rest. For each combination, we calculate the score and finally return the best score.

best_points = 0
for n0 in range(100):
for n1 in range(100 - n0):
for n2 in range(100 - n1 - n0):
n3 = 100 - n2 - n1 - n0
capacity = sum_stat(cookie_stats, "capacity", n0, n1, n2, n3)
durability = sum_stat(cookie_stats, "durability", n0, n1, n2, n3)
flavor = sum_stat(cookie_stats, "flavor", n0, n1, n2, n3)
texture = sum_stat(cookie_stats, "texture", n0, n1, n2, n3)
points = capacity * durability * flavor * texture
best_points = max(best_points, points)

In the code above, sum_stats just sums the chosen attribute over all ingredients. The program was quick enough, so no further optimization was needed.

Part 2

In part 2, we add another constraint. An until-known-ignored attributed has to be a specific value. This was quickly added to the brute force search with combinations not fulfilling the requirements skipped.

...
calories = sum_stat(cookie_stats, "calories", n0, n1, n2, n3)
if calories != 500:
continue
...

The runtime of the brute force was still quick enough, so still no optimization needed.

No comments:

Post a Comment