I'm trying to write a bin-packing program using worst-fit heuristic so that the it adds weights into bins until they cannot store any more as they are read by the file and put the sequence of bins into a priority queue so that it places the bin with the least remaining space on the top. But I'm having trouble with writing the comparator of the Bin class. Here's the full code:
public class BinPacking{
public static class Bin implements Comparable<Bin> {
int ID ;
int remSpace;
ArrayList<Integer> weights = new ArrayList<Integer>();
public Bin(int ID){
this.ID = ID;
remSpace = 100;
}
public void add(int size){
remSpace -= size;
weights.add(size);
}
@Override
public int compareTo(Bin o) {
return remSpace;
}
}
public static void main(String[] args) throws FileNotFoundException{
PriorityQueue<Bin> pq =new PriorityQueue<Bin>();
File myFile = new File("input.txt");
int binId = 1;
Bin d = new Bin(binId);
pq.add(d);
int size;
Scanner input = new Scanner(myFile);
while (input.hasNext())
{
size = input.nextInt();
d = (Bin)pq.peek();
if (d.remSpace >= size)
{
pq.remove(d);
d.add(size);
pq.add(d);
}
else
{
binId++;
d = new Bin(binId);
d.add(size);
pq.add(d);
}
}
System.out.println("Number of bins used: " + binId);
int mylst[][] = new int[binId][1000];
int k =1;
for(int i=0;i<binId;i++){
System.out.println("Bin" + k + ": ");
k++;
for(int j=0;j<pq.peek().weights.size();j++){
mylst[i][j] = pq.peek().weights.get(j);
System.out.print(" "+mylst[i][j]);
}
System.out.println();
pq.poll();
}
}
}