这个有两个方案:
1.每个都装得最满,减少瓶子容积损失
//xzlist 瓶子容积排序 tj水总体积 xzzc各个体积瓶子数
public static void Boxjs(int tj, List<Map<String,Object>> xzlist, List<Map<String,Object>> xzzc){
boolean flg = true;
String xzmc1="";
Integer xzrj1=0;
if (tj>0) {
for (int i = 0; i < xzlist.size(); i++) {
Integer xzrj = (Integer) xzlist.get(i).get("xzrj");
String xzmc = (String) xzlist.get(i).get("xzmc");
if (tj >= xzrj) {
xzmc1 = xzmc;
xzrj1 = xzrj;
break;
} else {
if (i == xzlist.size() - 1) {
xzmc1 = xzmc;
xzrj1 = xzrj;
}
}
}
for (Map<String, Object> zc : xzzc
) {
if (zc.get("xzmc").equals(xzmc1)) {
zc.put("sl", ((Integer) zc.get("sl")) + 1);
flg = false;
}
}
if (flg) {
Map<String, Object> map = new HashMap<>();
map.put("xzmc", xzmc1);
map.put("sl", 1);
xzzc.add(map);
}
Boxjs(tj - xzrj1, xzlist, xzzc);
}
}
调用
List<Map<String,Object>> xzlist=new ArrayList<>();
List<Map<String,Object>> xzzc=new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("xzmc", "100容积瓶子");
map.put("xzrj",100 );
Map<String, Object> map1 = new HashMap<>();
map1.put("xzmc", "50容积瓶子");
map1.put("xzrj",50 );
Map<String, Object> map2 = new HashMap<>();
map2.put("xzmc", "30容积瓶子");
map2.put("xzrj",30 );
Map<String, Object> map3 = new HashMap<>();
map3.put("xzmc", "20容积瓶子");
map3.put("xzrj",20 );
Map<String, Object> map4 = new HashMap<>();
map4.put("xzmc", "10容积瓶子 ");
map4.put("xzrj",10);
xzlist.add(map);
xzlist.add(map1);
xzlist.add(map2);
xzlist.add(map3);
xzlist.add(map4);
Boxjs(151,xzlist,xzzc);
xzzc.forEach(stm1 -> System.out.println(stm1));
2.少瓶子方案,使用最少瓶子:
//xzlist 瓶子容积排序 tj水总体积 xzzc各个体积瓶子数
public static void LBoxjs(int tj, List<Map<String,Object>> xzlist, List<Map<String,Object>> xzzc){
boolean flg = true;
String xzmc1="";
Integer xzrj1=0;
if (tj>0) {
for (int i = xzlist.size()-1; i >=0; i--) {
Integer xzrj = (Integer) xzlist.get(i).get("xzrj");
String xzmc = (String) xzlist.get(i).get("xzmc");
if (tj <= xzrj) {
xzmc1 = xzmc;
xzrj1 = xzrj;
break;
} else {
if (i ==0) {
xzmc1 = (String) xzlist.get(0).get("xzmc");
xzrj1 = (Integer) xzlist.get(0).get("xzrj");
break;
}
}
}
for (Map<String, Object> zc : xzzc
) {
if (zc.get("xzmc").equals(xzmc1)) {
zc.put("sl", ((Integer) zc.get("sl")) + 1);
flg = false;
}
}
if (flg) {
Map<String, Object> map = new HashMap<>();
map.put("xzmc", xzmc1);
map.put("sl", 1);
xzzc.add(map);
}
LBoxjs(tj - xzrj1, xzlist, xzzc);
}
}