Created
December 5, 2012 17:27
-
-
Save melix/4217688 to your computer and use it in GitHub Desktop.
Constraint programming + @CompileStatic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@GrabResolver('http://www.emn.fr/z-info/choco-repo/mvn/repository/') | |
@Grab('choco:choco-solver:2.1.5') | |
import static choco.Choco.* | |
import choco.cp.model.CPModel | |
import choco.cp.solver.CPSolver | |
import choco.kernel.model.variables.integer.IntegerVariable | |
@groovy.transform.CompileStatic | |
def solve(Map<String,Integer> menu, int sum) { | |
def m = new CPModel() | |
def s = new CPSolver() | |
def numOrdered = new IntegerVariable[menu.size()] | |
def priceEach = new int[menu.size()] | |
menu.eachWithIndex { String name, int price, int i -> | |
// number ordered >= 0 | |
// number ordered * price <= sum | |
numOrdered[i] = makeIntVar(name, 0, sum.intdiv(price)) | |
priceEach[i] = price | |
} | |
m.addConstraint(eq(scalar(numOrdered, priceEach), sum)) | |
s.read(m) | |
def more = s.solve() | |
while (more) { | |
println "Found a solution:" | |
numOrdered.each { IntegerVariable it -> | |
def v = s.getVar(it) | |
if (v.val) println " $v.val * $v.name" | |
} | |
more = s.nextSolution() | |
} | |
} | |
solve ([ | |
'Mixed fruit' : 215, | |
'French fries' : 275, | |
'Side salad' : 335, | |
'Hot wings' : 355, | |
'Mozzarella sticks' : 420, | |
'Sampler plate' : 580 | |
], 1505) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment