Packing problem, greedy algorithms seek approximate optimal solution
The code copy is as follows:
import java.util.Arrays;
import java.util.Comparator;
// Packing problem, greedy algorithm
public class Enchase {
public void test1() {
Integer[] boxes={34,6,40,2,23,12,12};
int boxCaptation=40;//Box capacity
//Inverse order
Arrays.sort(boxs, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
int unEnchase=boxs.length;//Number of unboxed
int minIndex=boxs.length-1;//The smallest box points to
while (unEnchase>0) {
for(int i=0;i<boxs.length;i++){
//The weight of the position box is zero skip
if(boxs[i]==0){
continue;
}
unEnchase--;
while((boxCaptation-boxs[i])>=boxs[minIndex]){
int k=i+1;
for(;k>i;k++){
//The weight of the position box is zero skip
if(boxs[k]==0){
continue;
}
//Add the box and clear the original position
boxes[i]+=boxs[k];
int temp=boxs[k];
boxes[k]=0;
unEnchase--;
if(boxs[i]>boxCaptation){
//The maximum capacity can be exceeded, the status will be restored
unEnchase++;
boxes[k]=temp;
boxes[i]-=boxs[k];
continue;
}
// Minimum box update
if(k==minIndex){
for(int y=minIndex;y>0;y--){
if(boxs[y]!=0){
minIndex=y;
}
}
}
break;
}
}
}
}
//Count the number of boxes
int Boxcount=0;
System.out.println("Boxing result:");
for(int i=0;i<boxs.length;i++){
System.out.print(boxs[i]+"/t");
if(boxs[i]==0){
continue;
}
Boxcount++;
}
System.out.println("/nNumber of boxes:"+Boxcount);
}
public static void main(String[] args) {
new Enchase().test1();
}
}
The above is all about this article, I hope you like it.