11package com .shekhargulati .ninetynine_problems .java8 ._00_random .tadm .ch03 ;
22
3- import java .util .Optional ;
4- import java .util .TreeSet ;
3+ import java .util .*;
54
65/**
76 * <p>In the bin-packing problem, we are given n metal objects, each weighing between zero and one kilogram.
@@ -19,13 +18,27 @@ public class Problem3_10 {
1918
2019 public static void main (String [] args ) {
2120 Problem3_10 p = new Problem3_10 ();
22- System .out .println (p .numberOfBins (new int []{100 , 200 , 600 , 500 , 400 , 1000 }));
23- System .out .println (p .numberOfBins (new int []{100 , 200 , 300 , 400 }));
21+ // System.out.println(p.numberOfBins(new int[]{100, 200, 600, 500, 400, 1000}));
22+ // System.out.println(p.numberOfBins(new int[]{100, 200, 600, 500, 400, 1000}));
23+ int bestCaseBins = p .numberOfBins_bestCase (new int []{500 , 600 , 300 , 500 });
24+ int worstCaseBins = p .numberOfBins_worstCase (new int []{500 , 600 , 300 , 500 });
25+ System .out .println ("best case: " + bestCaseBins );
26+ System .out .println ("worst case: " + worstCaseBins );
2427 }
2528
26- public int numberOfBins (int [] weights ) {
2729
28- TreeSet <Bin > bins = new TreeSet <>();
30+ public int numberOfBins_bestCase (int [] weights ) {
31+ return numberOfBins (weights , (b1 , b2 ) -> b1 .remaining () - b2 .remaining ());
32+ }
33+
34+ public int numberOfBins_worstCase (int [] weights ) {
35+ return numberOfBins (weights , (b1 , b2 ) -> b2 .remaining () - b1 .remaining ());
36+ }
37+
38+
39+ public int numberOfBins (int [] weights , Comparator <Bin > comparator ) {
40+
41+ TreeSet <Bin > bins = new TreeSet <>(comparator );
2942 /*
3043 * Iterate over all the weights in an array
3144 * For each weight find the bin which will have least remaining space after weight is put
@@ -53,17 +66,20 @@ private Optional<Bin> findBin(TreeSet<Bin> bins, int weight) {
5366
5467}
5568
56- class Bin implements Comparable < Bin > {
69+ class Bin {
5770 final int max = 1000 ;
5871 int currentConsumption = 0 ;
72+ List <Integer > weights = new ArrayList <>();
5973
6074 public Bin (int currentConsumption ) {
75+ weights .add (currentConsumption );
6176 this .currentConsumption = currentConsumption ;
6277 }
6378
6479 public Bin updateCurrentConsumption (int weight ) {
65- if (this .remaining () - weight > 0 ) {
80+ if (this .remaining () - weight >= 0 ) {
6681 this .currentConsumption += weight ;
82+ weights .add (weight );
6783 }
6884 return this ;
6985 }
@@ -73,8 +89,4 @@ public int remaining() {
7389 }
7490
7591
76- @ Override
77- public int compareTo (Bin o ) {
78- return this .remaining () - o .remaining ();
79- }
8092}
0 commit comments