C language to implement greedy algorithm of boxing problem _java

Source: Internet
Author: User

Packing problem, greedy algorithm to find the approximate optimal solution

Copy Code code as follows:

Import Java.util.Arrays;
Import Java.util.Comparator;
Packing problem, greedy algorithm
public class Enchase {
public void Test1 () {
Integer[] boxs={34,6,40,2,23,12,12};
int boxcaptation=40;//Box capacity
Reverse
Arrays.sort (Boxs, New comparator<integer> () {
@Override
public int Compare (integer o1, integer o2) {
return o2-o1;
}
});
int unenchase=boxs.length;//unboxed Number
int minindex=boxs.length-1;//the smallest box pointing
while (unenchase>0) {
for (int i=0;i<boxs.length;i++) {
Position box weight of 0 skipped
if (boxs[i]==0) {
Continue
}
unenchase--;
while ((Boxcaptation-boxs[i]) >=boxs[minindex]) {
int k=i+1;
for (; k>i;k++) {
Position box weight of 0 skipped
if (boxs[k]==0) {
Continue
}
Add the box to the original position clear zero
BOXS[I]+=BOXS[K];
int temp=boxs[k];
boxs[k]=0;
unenchase--;
if (boxs[i]>boxcaptation) {
More than maximum capacity, state recovery
unenchase++;
Boxs[k]=temp;
BOXS[I]-=BOXS[K];
Continue
}
Minimum box update
if (K==minindex) {
for (int y=minindex;y>0;y--) {
if (boxs[y]!=0) {
Minindex=y;
}
}
}
Break
}
}
}
}
Statistics Box Number
int boxcount=0;
SYSTEM.OUT.PRINTLN ("Packing result:");
for (int i=0;i<boxs.length;i++) {
System.out.print (boxs[i]+ "T");
if (boxs[i]==0) {
Continue
}
boxcount++;
}
System.out.println ("\ n Box Number:" +boxcount);
}
public static void Main (string[] args) {
New Enchase (). Test1 ();
}
}

The above is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.