r/adventofcode • • Dec 15 '15

SOLUTION MEGATHREAD --- Day 15 Solutions ---

This thread will be unlocked when there are a significant amount of people on the leaderboard with gold stars.

Edit: I'll be lucky if this post ever makes it to reddit without a 500 error. Have an unsticky-thread.

Edit2: c'mon, reddit... Leaderboard's capped, lemme post the darn thread...

Edit3: ALL RIGHTY FOLKS, POST THEM SOLUTIONS!

We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.

Please and thank you, and much appreciated!


--- Day 15: Science for Hungry People ---

Post your solution as a comment. Structure your post like previous daily solution threads.

11 Upvotes

174 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Dec 16 '15 edited Dec 16 '15

Your generator is eerily close to mine. :)

import operator
from functools import reduce

class Ingredient:

   def __init__(self, input):

      self.name, characteristics = input.strip().split(":")

      for characteristic in characteristics.split(", "):
         name, value = characteristic.split()
         setattr(self, name, int(value))

class Cookie:

   def __init__(self, ingredients, amounts, calorie_target=None):

      L = list(zip(ingredients, amounts))

      if calorie_target is None or self._sum_all(L, "calories") == calorie_target
         characteristics = [ "capacity", "durability", "flavor", "texture" ]
         maximums = [ max(0, self._sum_all(L, c)) for c in characteristics ]
         self.score = reduce(operator.mul, maximums) 
      else:
         self.score = 0

   def _sum_all(self, L, characteristic):

      return sum(getattr(i[0], characteristic) * i[1] for i in L)

def combinations(total, length):

   if length == 1: yield [total]
   if length <= 1: raise StopIteration

   for first in range(0, total + 1):
      for suffix in combinations(total - first, length - 1):
         yield [first] + suffix

with open("day15.in", "r") as f:
   ingredients = [ Ingredient(line) for line in f.readlines() ]

score_target = 100
part1, part2 = 0, 0

for L in combinations(score_target, len(ingredients)):
   part1 = max(part1, Cookie(ingredients, L).score)
   part2 = max(part2, Cookie(ingredients, L, calorie_target=500).score)

print("{} {}".format(part1, part2))