I have the following transportation problem.
Below you can see the source code I'm using.
final static int[] demandV = {30, 20, 70, 30, 60};
final static int[] supplyV = {50, 60, 50, 50};
final static int[][] costs = {{16, 16, 13, 22, 17},
{14, 14, 13, 19, 15},
{19, 19, 20, 23, 50},
{50, 12, 50, 15, 11}};
final static int supplyLength = supplyV.length;
final static int demandLength = demandV.length;
Model model = new Model();
IntVar[] demand = model.intVarArray("demand", demandLength, new int[] {30, 20, 70, 30, 60});
IntVar[] supply = model.intVarArray("supply", supplyLength, new int[] {50, 60, 50, 50});
IntVar[][] result = new IntVar[supplyLength][demandLength];
////
for (int i = 0; i < demandLength; i++) {
demand[i] = model.intVar("demand_" + i, demandV[i]);
}
////
for (int i = 0; i < supplyLength; i++) {
supply[i] = model.intVar("supply_" + i, supplyV[i]);
}
for (int i = 0; i < supplyLength; i++) {
for (int j = 0; j < demandLength; j++) {
result[i][j] = model.intVar("result_" + i + j, 0,100);
}
}
//sum of row values < supply
for (int i = 0; i < supplyLength; i++) {
model.sum(result[i],"<=",supply[i]).post();
}
//sum of column values < demand
for(int i = 0; i < demandLength; i++) {
IntVar[] col = new IntVar[supplyLength];
for(int j = 0; j < supplyLength; j++) {
col[j] = result[j][i];
}
model.sum(col, "<=", demand[i]).post(); // columns
}
IntVar tot_cost = model.intVar("tot_cost", 0, 9999, true);
//x[i][j]*costs[i][j]
int[] rows = new int[demandLength * supplyLength];
IntVar[] resultCost = new IntVar[demandLength * supplyLength];
int k = 0;
for (int i = 0; i < supplyLength; i++) {
for (int j = 0; j < demandLength; j++) {
rows[k] = costs[i][j];
resultCost[k] = result[i][j];
k++;
}
}
model.scalar(resultCost, rows, "=", tot_cost).post();
model.setObjective(Model.MINIMIZE, tot_cost);
Solver solver = model.getSolver();
solver.showSolutions();
solver.showShortStatistics();
while(solver.solve())
{
prettyPrint(model, tot_cost, result);
}
}
private void prettyPrint(Model model, IntVar tot_cost, IntVar[][] result) {
StringBuilder st = new StringBuilder();
st.append("Solution #").append(model.getSolver().getSolutionCount()).append("\n");
for (int i = 0; i < supplyLength; i++) {
for (int j = 0; j < demandLength; j++) {
st.append(result[i][j]).append(" ");
}
st.append("\n");
}
st.append("\tTotal C: ").append(tot_cost.getValue());
System.out.println(st.toString());
}