对于装箱问题,可能很容易找到使用不同算法的箱数。因此,应该有一种方法来确定权重是否适合特定的箱子。
下面的函数使用First Fit算法返回bin的数量。如何返回每个bin信息(哪个bin包含哪些权重)? 在此先感谢:)
public String firstFit(int[]listWeight, int capBin) {
int res = 0;
// Initialize result (Count of bins)
// Create an array to store remaining space in bins
// there can be at most n bins
int size=listWeight.length;
int[] bin_rem= new int[size];
// Place items one by one
for (int i=0; i<size; i++)
{
// Find the best bin that ca\n accomodate
// weight[i]
int j;
// Initialize minimum space left and index
// of best bin
int min = capBin+1, bi = 0;
for (j=0; j<res; j++)
{
if (bin_rem[j] >= listWeight[i] &&
bin_rem[j] - listWeight[i] < min)
{
bi = j;
min = bin_rem[j] -listWeight[i];
}
}
// If no bin could accommodate weight[i],
// create a new bin
if (min==capBin+1)
{
bin_rem[res] = capBin - listWeight[i];
res++;
}
else // Assign the item to best bin
bin_rem[bi] -= listWeight[i];
}
return "Number of bin needed: "+res+";
}
//代码,我试图返回一个包含所有bin信息的字符串。
public class Bin {
private int space;
private int [] attribute;
public Bin () {
}
public int getSpace() {
return space;
}
public void setSpace(int space) {
this.space = space;
}
public int getAttribute(int a) {
return attribute[a];
}
public void setAttribute(int[] attribute) {
this.attribute = attribute;
}
public void addAttribute(int a, int b) {
this.attribute[a]=b;
}
}
//功能
public String firstFit(int weight[], int cap ){
int count=0,i,j;
int len=weight.length,space;
Bin [] bin= new Bin[len];
for (i=0;i<len;i++) {
bin[i].setSpace(cap);
for (j=0;j<len;j++) {
space=bin[j].getSpace();
if (space >= weight[i]) {
bin[j].addAttribute(j, weight[i]);
bin[j].setSpace(space-weight[i]);
count=j+1;
}
}
}
StringBuilder rs = new StringBuilder();
rs.append(" Number of bin needed : "+ count );
for(i=0;i<count;i++) {
rs.append("Bin ["+i+1+"]'s weights : ");
for(j=0;j<len;j++) {
rs.append(bin[i].getAttribute(j)+" |");
}
}
String ms=rs.toString();
return ms;
}