1+ package com .shekhargulati .ninetynine_problems .java8 ._00_random .tadm .ch03 ;
2+
3+ import java .util .Optional ;
4+ import java .util .TreeSet ;
5+
6+ /**
7+ * <p>In the bin-packing problem, we are given n metal objects, each weighing between zero and one kilogram.
8+ * Our goal is to find the smallest number of bins that will hold the n objects, with each bin holding one kilogram at most.</p>
9+ * <p>
10+ * <p>* The best-fit heuristic for bin packing is as follows. Consider the objects in the order in which they are given.
11+ * For each object, place it into the partially filled bin with the smallest amount of extra room after the object is inserted.
12+ * If no such bin exists, start a new bin. Design an algorithm that implements the best-fit heuristic
13+ * (taking as input the n weights w1,w2,...,wn and outputting the number of bins used) in O(n log n) time.</p>
14+ * <p>
15+ * <p>* Repeat the above using the worst-fit heuristic, where we put the next object in the partially filled bin with the
16+ * largest amount of extra room after the object is inserted.</p>
17+ */
18+ public class Problem3_10 {
19+
20+ public static void main (String [] args ) {
21+ 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 }));
24+ }
25+
26+ public int numberOfBins (int [] weights ) {
27+
28+ TreeSet <Bin > bins = new TreeSet <>();
29+ /*
30+ * Iterate over all the weights in an array
31+ * For each weight find the bin which will have least remaining space after weight is put
32+ * If the bin is found then update its data
33+ * else create a new bin and add it to the set
34+ */
35+
36+ for (int weight : weights ) {
37+ Optional <Bin > foundBin = Optional .empty ();
38+ if (!bins .isEmpty ()) {
39+ foundBin = findBin (bins , weight );
40+ }
41+ if (foundBin .isPresent ()) {
42+ foundBin .get ().updateCurrentConsumption (weight );
43+ } else {
44+ bins .add (new Bin (weight ));
45+ }
46+ }
47+ return bins .size ();
48+ }
49+
50+ private Optional <Bin > findBin (TreeSet <Bin > bins , int weight ) {
51+ return bins .stream ().filter (b -> b .remaining () >= weight ).findFirst ();
52+ }
53+
54+ }
55+
56+ class Bin implements Comparable <Bin > {
57+ final int max = 1000 ;
58+ int currentConsumption = 0 ;
59+
60+ public Bin (int currentConsumption ) {
61+ this .currentConsumption = currentConsumption ;
62+ }
63+
64+ public Bin updateCurrentConsumption (int weight ) {
65+ if (this .remaining () - weight > 0 ) {
66+ this .currentConsumption += weight ;
67+ }
68+ return this ;
69+ }
70+
71+ public int remaining () {
72+ return this .max - this .currentConsumption ;
73+ }
74+
75+
76+ @ Override
77+ public int compareTo (Bin o ) {
78+ return this .remaining () - o .remaining ();
79+ }
80+ }
0 commit comments