Advertisement
jangxx

AoC 2019 Day 14 Part 1

Dec 14th, 2019
460
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. from gurobipy import *
  2. import re
  3.  
  4. ruleRe = re.compile("(\d+) (\w+)")
  5.  
  6. with open("input14.txt") as f:
  7.     model = Model("fuel")
  8.  
  9.     chemicals = {}
  10.     ruleVars = {}
  11.     chemicals2rules = {}
  12.  
  13.     rules = []
  14.  
  15.     model.modelSense = GRB.MINIMIZE
  16.  
  17.     for i,line in enumerate(f):
  18.         rule = line.split("=>")
  19.  
  20.         lh = [ ruleRe.match(r.strip()).groups() for r in rule[0].strip().split(",") ]
  21.         rh = ruleRe.match(rule[1].strip()).groups()
  22.  
  23.         # add vars
  24.         for quant,chem in lh:
  25.             if not chem in chemicals:
  26.                 chemicals2rules[chem] = { "lh": [], "rh": [] }
  27.                 chemicals[chem] = model.addVar(vtype=GRB.INTEGER, lb=0, obj=1)
  28.  
  29.             chemicals2rules[chem]["lh"].append((i, int(quant)))
  30.  
  31.         if not rh[1] in chemicals:
  32.             chemicals2rules[rh[1]] = { "lh": [], "rh": [] }
  33.             chemicals[rh[1]] = model.addVar(vtype=GRB.INTEGER, lb=0, obj=1)
  34.  
  35.         chemicals2rules[rh[1]]["rh"].append((i, int(rh[0])))
  36.  
  37.         ruleVars[i] = model.addVar(vtype=GRB.INTEGER, lb=0, obj=0)
  38.    
  39.         rules.append((lh, rh))
  40.  
  41.     # add rules
  42.     for chem in chemicals:
  43.         if len(chemicals2rules[chem]["rh"]) > 0:
  44.             # the quantity of chemicals is equal to the produced amount
  45.             model.addConstr(quicksum(quant * ruleVars[rule] for rule,quant in chemicals2rules[chem]["rh"]) == chemicals[chem])
  46.  
  47.         if len(chemicals2rules[chem]["lh"]) > 0:
  48.             # the quantity of chemicals has to be equal or larger than the needed amount for all rules
  49.             model.addConstr(quicksum(quant * ruleVars[rule] for rule,quant in chemicals2rules[chem]["lh"]) <= chemicals[chem])
  50.  
  51.     # produce exactly one fuel
  52.     model.addConstr(chemicals["FUEL"] == 1)
  53.  
  54.     model.optimize()
  55.  
  56.     # print solution
  57.     for chem in chemicals:
  58.         print("Require {} of type {}".format(chemicals[chem].x, chem))
  59.  
  60.     for r in ruleVars:
  61.         print("Rule {} was applied {} times".format(r, ruleVars[r].x))
  62.  
  63.     print(chemicals["ORE"].x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement