class Commodity {
String name;
int value;
int weight;
public Commodity(String n, int w, int v) {
name = n;
value = v;
weight = w;
}
public static void getMaxValueBad(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 current = 0;
while (pos > 0) {
if ((pos & 1) == 1) {
weight += commodities[current].weight;
value += commodities[current].value;
}
pos = pos >> 1;
++current;
}
if (weight <= capacity && maxValue < value) {
maxValue = value;
maxValuePos = i;
}
}
if (maxValuePos > 0) {
int current = 0;
System.out.println("我想要拿取:");
while (maxValuePos > 0) {
if ((maxValuePos & 1) == 1) {
System.out.println(commodities[current].name+"("+commodities[current].weight+","+commodities[current].value+");");
}
maxValuePos = maxValuePos >> 1;
++current;
}
}
}
public static void main(String[] args) {
Commodity[] commodities = {
new Commodity("吉他", 15, 1500),
new Commodity("笔记本电脑", 20, 2000),
new Commodity("音响", 30, 3000)
};
getMaxValueBad(35, commodities, 3);
Commodity[] commodities2 = {
new Commodity("吉他", 15, 1500),
new Commodity("笔记本电脑", 20, 2000),
new Commodity("音响", 30, 3000),
new Commodity("iPad",5,4000)
};
getMaxValueBad(40, commodities2, 4);
}
}