public static void knapsack(int numOfItem, int numOfWeight) {
int[] profit = new int[numOfItem+1];
int[] weight = new int[numOfItem+1];
for (int n=1; n<=numOfItem; n++) {
profit[n] = (int)(Math.random()*1000);
weight[n] = (int)(Math.random()*numOfWeight);
}
int[][] opt = new int[numOfItem+1][numOfWeight+1];
boolean[][] sol = new boolean[numOfItem+1][numOfWeight+1];
for (int n=1; n<=numOfItem; n++) {
for (int w=1; w<=numOfWeight; w++) {
int option1 = opt[n-1][w];
int option2 = Integer.MIN_VALUE;
if (weight[n]<=w) option2 = profit[n] + opt[n-1][w-weight[n]];
opt[n][w] = Math.max(option1, option2);
sol[n][w] = (option2>option1);
}
}
// determine which items to take
boolean[] take = new boolean[numOfItem+1];
for (int n = numOfItem, w = numOfWeight; n > 0; n--) {
if (sol[n][w]) { take[n] = true; w = w - weight[n]; }
else { take[n] = false; }
}
// print results
System.out.println("item" + "\t" + "profit" + "\t" + "weight" + "\t" + "take");
for (int n = 1; n <= numOfItem; n++) {
System.out.println(n + "\t" + profit[n] + "\t" + weight[n] + "\t" + take[n]);
}
}
public static void main(String[] args) {
knapsack(6, 2000);
}
No comments:
Post a Comment