| |||||||||||||||
Burglar - Use of index sets, formulating logical constraints Description Several versions of a simple knapsack problem:
Source Files By clicking on a file name, a preview is opened at the bottom of this page.
xbburgi.java /******************************************************** * Xpress-BCL Java Example Problems * ================================ * * file xbburgi.java * ````````````````` * Burglar problem. * Binary variable formulation with index sets. * * (c) 2008-2024 Fair Isaac Corporation * author: S.Heipcke, Jan. 2000, rev. Mar. 2011 ********************************************************/ import com.dashoptimization.*; public class xbburgi { /****DATA****/ /* Item: ca ne va pi tv vi ch br */ static final double[] VALUE = {15, 100, 90, 60, 40, 15, 10, 1}; /* Value of items */ static final double[] WEIGHT = {2, 20, 20, 30, 40, 30, 60, 10}; /* Weight of items */ static final double WTMAX = 102; /* Max weight allowed for haul */ static final String[] ITEMNAMES = { "camera", "necklace", "vase", "picture", "tv", "video", "chest", "brick" }; static int NItems; /* Number of items */ public static void main(String[] args) { try (XPRBprob p = new XPRBprob("Burglari"); /* Initialize BCL and create a new problem */ XPRBexprContext context = new XPRBexprContext() /* Release XPRBexpr instances at end of block. */) { XPRBvar[] x; XPRBindexSet ITEMS; /* Set of items */ int i; XPRBexpr lobj, kn; /****INDICES****/ ITEMS = p.newIndexSet("Items", ITEMNAMES.length); /* Create the index set */ for (i = 0; i < ITEMNAMES.length; i++) ITEMS.addElement(ITEMNAMES[i]); NItems = ITEMS.getSize(); /* Get the size of the index set */ /****VARIABLES****/ x = new XPRBvar[NItems]; for (i = 0; i < NItems; i++) x[i] = p.newVar("x_" + ITEMS.getIndexName(i), XPRB.BV); /* 1 if we take item i; 0 otherwise */ /****OBJECTIVE****/ lobj = new XPRBexpr(); for (i = 0; i < NItems; i++) lobj.add(x[i].mul(VALUE[i])); p.setObj(lobj); /* Set objective: maximize total value */ /****CONSTRAINTS****/ kn = new XPRBexpr(); for (i = 0; i < NItems; i++) kn.add(x[i].mul(WEIGHT[i])); p.newCtr("WtMax", kn.lEql(WTMAX)); /* Weight restriction */ /****SOLVING + OUTPUT****/ p.setSense(XPRB.MAXIM); /* Choose the sense of the optimization */ p.mipOptimize(""); /* Solve the MIP-problem */ System.out.println("Objective: " + p.getObjVal()); /* Get objective value */ for (i = 0; i < NItems; i++) /* Print out the chosen items */ if (x[i].getSol() > 0) System.out.println(ITEMS.getIndexName(i) + ": " + x[i].getSol()); } } } | |||||||||||||||
© Copyright 2024 Fair Isaac Corporation. |