Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from gurobipy import *
- import re
- ruleRe = re.compile("(\d+) (\w+)")
- with open("input14.txt") as f:
- model = Model("fuel")
- chemicals = {}
- ruleVars = {}
- chemicals2rules = {}
- rules = []
- model.modelSense = GRB.MINIMIZE
- for i,line in enumerate(f):
- rule = line.split("=>")
- lh = [ ruleRe.match(r.strip()).groups() for r in rule[0].strip().split(",") ]
- rh = ruleRe.match(rule[1].strip()).groups()
- # add vars
- for quant,chem in lh:
- if not chem in chemicals:
- chemicals2rules[chem] = { "lh": [], "rh": [] }
- chemicals[chem] = model.addVar(vtype=GRB.INTEGER, lb=0, obj=1)
- chemicals2rules[chem]["lh"].append((i, int(quant)))
- if not rh[1] in chemicals:
- chemicals2rules[rh[1]] = { "lh": [], "rh": [] }
- chemicals[rh[1]] = model.addVar(vtype=GRB.INTEGER, lb=0, obj=1)
- chemicals2rules[rh[1]]["rh"].append((i, int(rh[0])))
- ruleVars[i] = model.addVar(vtype=GRB.INTEGER, lb=0, obj=0)
- rules.append((lh, rh))
- # add rules
- for chem in chemicals:
- if len(chemicals2rules[chem]["rh"]) > 0:
- # the quantity of chemicals is equal to the produced amount
- model.addConstr(quicksum(quant * ruleVars[rule] for rule,quant in chemicals2rules[chem]["rh"]) == chemicals[chem])
- if len(chemicals2rules[chem]["lh"]) > 0:
- # the quantity of chemicals has to be equal or larger than the needed amount for all rules
- model.addConstr(quicksum(quant * ruleVars[rule] for rule,quant in chemicals2rules[chem]["lh"]) <= chemicals[chem])
- # produce exactly one fuel
- model.addConstr(chemicals["FUEL"] == 1)
- model.optimize()
- # print solution
- for chem in chemicals:
- print("Require {} of type {}".format(chemicals[chem].x, chem))
- for r in ruleVars:
- print("Rule {} was applied {} times".format(r, ruleVars[r].x))
- print(chemicals["ORE"].x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement