Skip to content

Instantly share code, notes, and snippets.

@hermanbanken
Last active August 29, 2015 14:17
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 hermanbanken/fba7c3603aaa5ccf74fa to your computer and use it in GitHub Desktop.
Save hermanbanken/fba7c3603aaa5ccf74fa to your computer and use it in GitHub Desktop.
Optimise Exact
import java.util.Arrays;
public class Main {
public static int startStock = 20;
public static int deliveryTime = 2;
public static int box = 30;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] buyings = new int[14];
int[] sales = new int[] { 0, 0, 10, 20, 30, 10, 20, 30, 45, 25, 5, 45, 45, 20 };
// Optimal
int[] bestBuyings = new int[14];
int bestCosts = Integer.MAX_VALUE;
int max = 2;
int iterations = (int) Math.pow(max+1, buyings.length);
System.out.println("Iterations: "+iterations);
//int show = 1000000;
while(iterations-- > 0){
int c = costs(startStock, buyings, sales);
//System.out.println("Eval: "+Arrays.toString(buyings) + "; costs = "+c);
if(c < bestCosts){
bestCosts = c;
bestBuyings = buyings.clone();
System.out.println("New best "+c+"! Go girl! "+Arrays.toString(bestBuyings));
}
next(buyings, max);
}
System.out.println("Buyings: "+Arrays.toString(bestBuyings));
System.out.println("Costs: "+bestCosts);
}
public static int[] next(int[] list, int max){
int curry = 1;
for(int i = 0; i < list.length; i++){
if(curry + list[i] > max){
list[i] = 0;
curry = 1;
} else {
list[i] += curry;
curry = 0;
}
}
return list;
}
public static int costs(int startStock, int[] buyPerMonth, int[] sales){
int totalCost = 0;
int[] stockAtTime = new int[buyPerMonth.length];
for(int m = 0; m < buyPerMonth.length; m++){
stockAtTime[m] = m == 0 ? startStock : stockAtTime[m-1];
// Deliveries
stockAtTime[m] += m >= deliveryTime ? buyPerMonth[m - deliveryTime]*box : 0;
// Penalty
int toLess = Math.max(0, sales[m] - stockAtTime[m]);
stockAtTime[m] -= Math.min(sales[m], stockAtTime[m]);
totalCost += toLess * 2000;
// Warehouse
totalCost += stockAtTime[m] * 400;
}
return totalCost;
}
}
@hermanbanken
Copy link
Author

Boxes: [0, 1, 1, 0, 1, 1, 1, 1, 0, 2, 1, 1, 0, 0]
Costs: 80000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment