class Commodity {
public String name;
public int value;
public int weight;
public Commodity(){}
public Commodity(String n, int w, int v){
this.name = n;
this.value = v;
this.weight = w;
}
public static void getMaxValueForBackpack(int capacity, Commodity commodities[], int commodityCount) {
int maxValue = -1;
int maxValuePos = -1;
for (int i = 0; i < Math.pow(2,commodityCount); i++) {
int pos = i;
int weight = 0;
int value = 0;
int curBit = 0;
while (pos > 0) {
int res = pos & 1;
if (res == 1) {
weight += commodities[curBit].weight;
value += commodities[curBit].value;
}
pos = pos >> 1;
++curBit;
}
if (weight <= capacity && maxValue < value) {
maxValue = value;
maxValuePos = i;
}
}
if (maxValuePos > 0) {
int curBit = 0;
System.out.println("I want to put ");
while (maxValuePos > 0) {
int res = maxValuePos & 1;
if (res == 1) {
System.out.print(commodities[curBit].name+"("+commodities[curBit].weight+","+commodities[curBit].value+");\n");
}
maxValuePos = maxValuePos >> 1;
++curBit;
}
}
}
public static void main(String[] args) {
Commodity commodities[] = {
new Commodity("吉他", 15, 1500),
new Commodity("笔记本电脑", 20, 2000),
new Commodity("音响", 30, 3000)};
getMaxValueForBackpack(35, commodities, 3);
}
}