Skip to content

Instantly share code, notes, and snippets.

@micxjo
Last active December 7, 2018 21:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micxjo/add29acb8d194b243594 to your computer and use it in GitHub Desktop.
Save micxjo/add29acb8d194b243594 to your computer and use it in GitHub Desktop.
import sys
from os import abort
from ortools.constraint_solver import pywrapcp
def day15(path, calorie_total=None):
solver = pywrapcp.Solver('AOC Day 15')
values = range(0, 100)
ingredients = []
caps, durs, flavs, texts, cals = [], [], [], [], []
with open(path) as f:
for line in f.readlines():
words = line.split(" ")
ingredient = solver.IntVar(values, words[0].strip(":"))
solver.Add(ingredient >= 0)
ingredients.append(ingredient)
caps.append(int(words[2].strip(",")))
durs.append(int(words[4].strip(",")))
flavs.append(int(words[6].strip(",")))
texts.append(int(words[8].strip(",")))
cals.append(int(words[10]))
solver.Add(solver.Sum(ingredients) == 100)
cap_sum = solver.Sum(
caps[i] * ingredients[i] for i in xrange(0, len(ingredients)))
dur_sum = solver.Sum(
durs[i] * ingredients[i] for i in xrange(0, len(ingredients)))
flav_sum = solver.Sum(
flavs[i] * ingredients[i] for i in xrange(0, len(ingredients)))
text_sum = solver.Sum(
texts[i] * ingredients[i] for i in xrange(0, len(ingredients)))
solver.Add(cap_sum >= 0)
solver.Add(dur_sum >= 0)
solver.Add(flav_sum >= 0)
solver.Add(text_sum >= 0)
if calorie_total is not None:
cal_sum = solver.Sum(
cals[i] * ingredients[i] for i in xrange(0, len(ingredients)))
solver.Add(cal_sum == calorie_total)
total = solver.IntVar(0, sys.maxint, "Total")
solver.Add(total == cap_sum * dur_sum * flav_sum * text_sum)
objective = solver.Maximize(total, 1)
db = solver.Phase(ingredients + [total],
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db, [objective])
best = None
best_ingredients = None
while solver.NextSolution():
best = total.Value()
best_ingredients = [(i.Name(), i.Value()) for i in ingredients]
print("Best total: {}, with: {}".format(best, best_ingredients))
solver.EndSearch()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Please enter an input filename")
day15(sys.argv[1])
day15(sys.argv[1], 500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment