Skip to content

Instantly share code, notes, and snippets.

@thetric
Created June 3, 2020 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thetric/20b3bc5c4f7e1eea3b04b06b22c55f42 to your computer and use it in GitHub Desktop.
Save thetric/20b3bc5c4f7e1eea3b04b06b22c55f42 to your computer and use it in GitHub Desktop.
Spicy pizza configurator
import org.chocosolver.solver.Model;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.variables.BoolVar;
import org.chocosolver.solver.variables.IntVar;
public class PizzaConf {
Model m = new Model();
Solver s = m.getSolver();
final int numBools = 6;
BoolVar[] toppings = m.boolVarArray(numBools);
int[] isSpicyCoefficients = new int[numBools];
IntVar isSpicyPizza = m.intVar("weightedSum", 0, numBools);
private PizzaConf() {
for (int i = 0; i < numBools; i++) {
isSpicyCoefficients[i] = i < 2 ? 1 : 0;
}
// is hot indicator
m.scalar(toppings, isSpicyCoefficients, "=", isSpicyPizza).post();
// at least one hot topping
m.arithm(isSpicyPizza, ">=", 1).post();
m.scalar(toppings, isSpicyCoefficients, ">=", 1).post();
// max elements selected
m.sum(toppings, "<=", 3).post();
System.out.println(">>> init");
propAndPrint();
postEqual(2);
propAndPrint();
postEqual(3);
propAndPrint();
postEqual(1);
// the following statement causes a contradiction exception:
// CONTRADICTION (PropXplusYeqZ(BV_1, BV_2, weightedSum), weightedSum = {1..2}) : new lower bound is greater than upper bound
// postEqual(4);
propAndPrint();
}
private void postEqual(int i) {
Constraint constraint = m.arithm(toppings[i], "=", 1);
System.out.println(">>> " + constraint);
constraint.post();
}
private void propAndPrint() {
try {
s.propagate();
} catch (ContradictionException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < numBools; i++) {
System.out.printf("%-16s %d%n", toppings[i], isSpicyCoefficients[i]);
}
System.out.println(isSpicyPizza);
System.out.println();
}
public static void main(String[] args) {
new PizzaConf();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment