Bin Packing Problem (Minimize number of used Bins)
Last Updated :
25 Apr, 2023
Given n items of different weights and bins each of capacity c, assign each item to a bin such that number of total used bins is minimized. It may be assumed that all items have weights smaller than bin capacity.
Example:
Input: weight[] = {4, 8, 1, 4, 2, 1}
Bin Capacity c = 10
Output: 2
We need minimum 2 bins to accommodate all items
First bin contains {4, 4, 2} and second bin {8, 1, 1}
Input: weight[] = {9, 8, 2, 2, 5, 4}
Bin Capacity c = 10
Output: 4
We need minimum 4 bins to accommodate all items.
Input: weight[] = {2, 5, 4, 7, 1, 3, 8};
Bin Capacity c = 10
Output: 3
Lower Bound
We can always find a lower bound on minimum number of bins required. The lower bound can be given as :
Min no. of bins >= Ceil ((Total Weight) / (Bin Capacity))
In the above examples, lower bound for first example is “ceil(4 + 8 + 1 + 4 + 2 + 1)/10” = 2 and lower bound in second example is “ceil(9 + 8 + 2 + 2 + 5 + 4)/10” = 3.
This problem is a NP Hard problem and finding an exact minimum number of bins takes exponential time. Following are approximate algorithms for this problem.
Applications
- Loading of containers like trucks.
- Placing data on multiple disks.
- Job scheduling.
- Packing advertisements in fixed length radio/TV station breaks.
- Storing a large collection of music onto tapes/CD’s, etc.
Online Algorithms
These algorithms are for Bin Packing problems where items arrive one at a time (in unknown order), each must be put in a bin, before considering the next item.
1. Next Fit:
When processing next item, check if it fits in the same bin as the last item. Use a new bin only if it does not.
Below is C++ implementation for this algorithm.
C++
#include <bits/stdc++.h>
using namespace std;
int nextFit( int weight[], int n, int c)
{
int res = 0, bin_rem = c;
for ( int i = 0; i < n; i++) {
if (weight[i] > bin_rem) {
res++;
bin_rem = c - weight[i];
}
else
bin_rem -= weight[i];
}
return res;
}
int main()
{
int weight[] = { 2, 5, 4, 7, 1, 3, 8 };
int c = 10;
int n = sizeof (weight) / sizeof (weight[0]);
cout << "Number of bins required in Next Fit : "
<< nextFit(weight, n, c);
return 0;
}
|
Java
class GFG {
static int nextFit( int weight[], int n, int c)
{
int res = 0 , bin_rem = c;
for ( int i = 0 ; i < n; i++) {
if (weight[i] > bin_rem) {
res++;
bin_rem = c - weight[i];
}
else
bin_rem -= weight[i];
}
return res;
}
public static void main(String[] args)
{
int weight[] = { 2 , 5 , 4 , 7 , 1 , 3 , 8 };
int c = 10 ;
int n = weight.length;
System.out.println( "Number of bins required in Next Fit : " + nextFit(weight, n, c));
}
}
|
Python3
def nextfit(weight, c):
res = 0
rem = c
for _ in range ( len (weight)):
if rem > = weight[_]:
rem = rem - weight[_]
else :
res + = 1
rem = c - weight[_]
return res
weight = [ 2 , 5 , 4 , 7 , 1 , 3 , 8 ]
c = 10
print ( "Number of bins required in Next Fit :" ,
nextfit(weight, c))
|
C#
using System;
class GFG
{
static int nextFit( int []weight, int n, int c)
{
int res = 0, bin_rem = c;
for ( int i = 0; i < n; i++)
{
if (weight[i] > bin_rem)
{
res++;
bin_rem = c - weight[i];
}
else
bin_rem -= weight[i];
}
return res;
}
public static void Main(String[] args)
{
int []weight = { 2, 5, 4, 7, 1, 3, 8 };
int c = 10;
int n = weight.Length;
Console.WriteLine( "Number of bins required" +
" in Next Fit : " + nextFit(weight, n, c));
}
}
|
Javascript
<script>
function nextFit(weight, n, c)
{
let res = 0, bin_rem = c;
for (let i = 0; i < n; i++)
{
if (weight[i] > bin_rem)
{
res++;
bin_rem = c - weight[i];
}
else
bin_rem -= weight[i];
}
return res;
}
let weight = [ 2, 5, 4, 7, 1, 3, 8 ];
let c = 10;
let n = weight.length;
document.write( "Number of bins required in Next Fit : " + nextFit(weight, n, c));
</script>
|
Output:
Number of bins required in Next Fit : 4
Next Fit is a simple algorithm. It requires only O(n) time and O(1) extra space to process n items.
Next Fit is 2 approximate, i.e., the number of bins used by this algorithm is bounded by twice of optimal. Consider any two adjacent bins. The sum of items in these two bins must be > c; otherwise, NextFit would have put all the items of second bin into the first. The same holds for all other bins. Thus, at most half the space is wasted, and so Next Fit uses at most 2M bins if M is optimal.
2. First Fit:
When processing the next item, scan the previous bins in order and place the item in the first bin that fits. Start a new bin only if it does not fit in any of the existing bins.
C++
#include <bits/stdc++.h>
using namespace std;
int firstFit( int weight[], int n, int c)
{
int res = 0;
int bin_rem[n];
for ( int i = 0; i < n; i++) {
int j;
for (j = 0; j < res; j++) {
if (bin_rem[j] >= weight[i]) {
bin_rem[j] = bin_rem[j] - weight[i];
break ;
}
}
if (j == res) {
bin_rem[res] = c - weight[i];
res++;
}
}
return res;
}
int main()
{
int weight[] = { 2, 5, 4, 7, 1, 3, 8 };
int c = 10;
int n = sizeof (weight) / sizeof (weight[0]);
cout << "Number of bins required in First Fit : "
<< firstFit(weight, n, c);
return 0;
}
|
Java
class GFG
{
static int firstFit( int weight[], int n, int c)
{
int res = 0 ;
int []bin_rem = new int [n];
for ( int i = 0 ; i < n; i++)
{
int j;
for (j = 0 ; j < res; j++)
{
if (bin_rem[j] >= weight[i])
{
bin_rem[j] = bin_rem[j] - weight[i];
break ;
}
}
if (j == res)
{
bin_rem[res] = c - weight[i];
res++;
}
}
return res;
}
public static void main(String[] args)
{
int weight[] = { 2 , 5 , 4 , 7 , 1 , 3 , 8 };
int c = 10 ;
int n = weight.length;
System.out.print( "Number of bins required in First Fit : "
+ firstFit(weight, n, c));
}
}
|
Python3
def firstFit(weight, n, c):
res = 0
bin_rem = [ 0 ] * n
for i in range (n):
j = 0
while ( j < res):
if (bin_rem[j] > = weight[i]):
bin_rem[j] = bin_rem[j] - weight[i]
break
j + = 1
if (j = = res):
bin_rem[res] = c - weight[i]
res = res + 1
return res
weight = [ 2 , 5 , 4 , 7 , 1 , 3 , 8 ]
c = 10
n = len (weight)
print ( "Number of bins required in First Fit : " ,firstFit(weight, n, c))
|
C#
using System;
class GFG
{
static int firstFit( int []weight, int n, int c)
{
int res = 0;
int []bin_rem = new int [n];
for ( int i = 0; i < n; i++)
{
int j;
for (j = 0; j < res; j++)
{
if (bin_rem[j] >= weight[i])
{
bin_rem[j] = bin_rem[j] - weight[i];
break ;
}
}
if (j == res)
{
bin_rem[res] = c - weight[i];
res++;
}
}
return res;
}
public static void Main(String[] args)
{
int []weight = { 2, 5, 4, 7, 1, 3, 8 };
int c = 10;
int n = weight.Length;
Console.Write( "Number of bins required in First Fit : "
+ firstFit(weight, n, c));
}
}
|
Javascript
<script>
function firstFit(weight,n,c)
{
let res = 0;
let bin_rem = new Array(n);
for (let i = 0; i < n; i++)
{
let j;
for (j = 0; j < res; j++)
{
if (bin_rem[j] >= weight[i])
{
bin_rem[j] = bin_rem[j] - weight[i];
break ;
}
}
if (j == res)
{
bin_rem[res] = c - weight[i];
res++;
}
}
return res;
}
let weight=[ 2, 5, 4, 7, 1, 3, 8];
let c = 10;
let n = weight.length;
document.write( "Number of bins required in First Fit : "
+ firstFit(weight, n, c));
</script>
|
Output:
Number of bins required in First Fit : 4
The above implementation of First Fit requires O(n2) time, but First Fit can be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.
If M is the optimal number of bins, then First Fit never uses more than 1.7M bins. So First-Fit is better than Next Fit in terms of upper bound on number of bins.
Auxiliary Space: O(n)
3. Best Fit:
The idea is to places the next item in the *tightest* spot. That is, put it in the bin so that the smallest empty space is left.
C++
#include <bits/stdc++.h>
using namespace std;
int bestFit( int weight[], int n, int c)
{
int res = 0;
int bin_rem[n];
for ( int i = 0; i < n; i++) {
int j;
int min = c + 1, bi = 0;
for (j = 0; j < res; j++) {
if (bin_rem[j] >= weight[i] && bin_rem[j] -
weight[i] < min) {
bi = j;
min = bin_rem[j] - weight[i];
}
}
if (min == c + 1) {
bin_rem[res] = c - weight[i];
res++;
}
else
bin_rem[bi] -= weight[i];
}
return res;
}
int main()
{
int weight[] = { 2, 5, 4, 7, 1, 3, 8 };
int c = 10;
int n = sizeof (weight) / sizeof (weight[0]);
cout << "Number of bins required in Best Fit : "
<< bestFit(weight, n, c);
return 0;
}
|
Java
class GFG
{
static int bestFit( int weight[], int n, int c)
{
int res = 0 ;
int []bin_rem = new int [n];
for ( int i = 0 ; i < n; i++)
{
int j;
int min = c + 1 , bi = 0 ;
for (j = 0 ; j < res; j++)
{
if (bin_rem[j] >= weight[i] &&
bin_rem[j] - weight[i] < min)
{
bi = j;
min = bin_rem[j] - weight[i];
}
}
if (min == c + 1 )
{
bin_rem[res] = c - weight[i];
res++;
}
else
bin_rem[bi] -= weight[i];
}
return res;
}
public static void main(String[] args)
{
int []weight = { 2 , 5 , 4 , 7 , 1 , 3 , 8 };
int c = 10 ;
int n = weight.length;
System.out.print( "Number of bins required in Best Fit : "
+ bestFit(weight, n, c));
}
}
|
Python3
def firstFit(weight, n, c):
res = 0 ;
bin_rem = [ 0 ] * n;
for i in range (n):
j = 0 ;
min = c + 1 ;
bi = 0 ;
for j in range (res):
if (bin_rem[j] > = weight[i] and bin_rem[j] -
weight[i] < min ):
bi = j;
min = bin_rem[j] - weight[i];
if ( min = = c + 1 ):
bin_rem[res] = c - weight[i];
res + = 1 ;
else :
bin_rem[bi] - = weight[i];
return res;
if __name__ = = '__main__' :
weight = [ 2 , 5 , 4 , 7 , 1 , 3 , 8 ];
c = 10 ;
n = len (weight);
print ( "Number of bins required in First Fit : " ,
firstFit(weight, n, c));
|
C#
using System;
class GFG {
static int bestFit( int [] weight, int n, int c)
{
int res = 0;
int [] bin_rem = new int [n];
for ( int i = 0; i < n; i++) {
int j;
int min = c + 1, bi = 0;
for (j = 0; j < res; j++) {
if (bin_rem[j] >= weight[i]
&& bin_rem[j] - weight[i] < min) {
bi = j;
min = bin_rem[j] - weight[i];
}
}
if (min == c + 1) {
bin_rem[res] = c - weight[i];
res++;
}
else
bin_rem[bi] -= weight[i];
}
return res;
}
public static void Main(String[] args)
{
int [] weight = { 2, 5, 4, 7, 1, 3, 8 };
int c = 10;
int n = weight.Length;
Console.Write(
"Number of bins required in Best Fit : "
+ bestFit(weight, n, c));
}
}
|
Javascript
<script>
function bestFit(weight , n , c) {
var res = 0;
var bin_rem = Array(n).fill(0);
for (i = 0; i < n; i++) {
var j;
var min = c + 1, bi = 0;
for (j = 0; j < res; j++) {
if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] < min) {
bi = j;
min = bin_rem[j] - weight[i];
}
}
if (min == c + 1) {
bin_rem[res] = c - weight[i];
res++;
} else
bin_rem[bi] -= weight[i];
}
return res;
}
var weight = [ 2, 5, 4, 7, 1, 3, 8 ];
var c = 10;
var n = weight.length;
document.write( "Number of bins required in Best Fit : " + bestFit(weight, n, c));
</script>
|
Output:
Number of bins required in Best Fit : 4
Best Fit can also be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.
If M is the optimal number of bins, then Best Fit never uses more than 1.7M bins. So Best Fit is same as First Fit and better than Next Fit in terms of upper bound on number of bins.
Auxiliary Space: O(n)
4. Worst Fit:
The idea is to places the next item in the least tight spot to even out the bins. That is, put it in the bin so that most empty space is left.
C++
#include <bits/stdc++.h>
using namespace std;
int worstFit( int weight[], int n, int c)
{
int res = 0;
int bin_rem[n];
for ( int i = 0; i < n; i++) {
int j;
int mx = -1, wi = 0;
for (j = 0; j < res; j++) {
if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) {
wi = j;
mx = bin_rem[j] - weight[i];
}
}
if (mx == -1) {
bin_rem[res] = c - weight[i];
res++;
}
else
bin_rem[wi] -= weight[i];
}
return res;
}
int main()
{
int weight[] = { 2, 5, 4, 7, 1, 3, 8 };
int c = 10;
int n = sizeof (weight) / sizeof (weight[0]);
cout << "Number of bins required in Worst Fit : "
<< worstFit(weight, n, c);
return 0;
}
|
Java
class GFG
{
static int worstFit( int weight[], int n, int c)
{
int res = 0 ;
int bin_rem[]= new int [n];
for ( int i = 0 ; i < n; i++)
{
int j;
int mx = - 1 , wi = 0 ;
for (j = 0 ; j < res; j++) {
if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) {
wi = j;
mx = bin_rem[j] - weight[i];
}
}
if (mx == - 1 ) {
bin_rem[res] = c - weight[i];
res++;
}
else
bin_rem[wi] -= weight[i];
}
return res;
}
public static void main(String[] args)
{
int weight[] = { 2 , 5 , 4 , 7 , 1 , 3 , 8 };
int c = 10 ;
int n = weight.length;
System.out.print( "Number of bins required in Worst Fit : " +worstFit(weight, n, c));
}
}
|
Python3
def worstFit( weight, n, c):
res = 0
bin_rem = [ 0 for i in range (n)]
for i in range (n):
mx,wi = - 1 , 0
for j in range (res):
if (bin_rem[j] > = weight[i] and bin_rem[j] - weight[i] > mx):
wi = j
mx = bin_rem[j] - weight[i]
if (mx = = - 1 ):
bin_rem[res] = c - weight[i]
res + = 1
else :
bin_rem[wi] - = weight[i]
return res
weight = [ 2 , 5 , 4 , 7 , 1 , 3 , 8 ]
c = 10
n = len (weight)
print (f "Number of bins required in Worst Fit : {worstFit(weight, n, c)}" )
|
C#
using System;
class GFG
{
static int worstFit( int []weight, int n, int c)
{
int res = 0;
int []bin_rem= new int [n];
for ( int i = 0; i < n; i++)
{
int j;
int mx = -1, wi = 0;
for (j = 0; j < res; j++) {
if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) {
wi = j;
mx = bin_rem[j] - weight[i];
}
}
if (mx == -1) {
bin_rem[res] = c - weight[i];
res++;
}
else
bin_rem[wi] -= weight[i];
}
return res;
}
public static void Main(String[] args)
{
int []weight = { 2, 5, 4, 7, 1, 3, 8 };
int c = 10;
int n = weight.Length;
Console.Write( "Number of bins required in Worst Fit : " +worstFit(weight, n, c));
}
}
|
Javascript
<script>
function worstFit( weight, n, c)
{
var res = 0;
var bin_rem = Array(n).fill(0);
for ( var i = 0; i < n; i++)
{
var j;
var mx = -1, wi = 0;
for (j = 0; j < res; j++) {
if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) {
wi = j;
mx = bin_rem[j] - weight[i];
}
}
if (mx == -1) {
bin_rem[res] = c - weight[i];
res++;
}
else
bin_rem[wi] -= weight[i];
}
return res;
}
var weight = [ 2, 5, 4, 7, 1, 3, 8 ];
var c = 10;
var n = weight.length;
document.write( "Number of bins required in Worst Fit : " +worstFit(weight, n, c));
</script>
|
Output:
Number of bins required in Worst Fit : 4
Worst Fit can also be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.
If M is the optimal number of bins, then Best Fit never uses more than 2M-2 bins. So Worst Fit is same as Next Fit in terms of upper bound on number of bins.
Auxiliary Space: O(n)
Offline Algorithms
In the offline version, we have all items upfront. Unfortunately offline version is also NP Complete, but we have a better approximate algorithm for it. First Fit Decreasing uses at most (4M + 1)/3 bins if the optimal is M.
4. First Fit Decreasing:
A trouble with online algorithms is that packing large items is difficult, especially if they occur late in the sequence. We can circumvent this by *sorting* the input sequence, and placing the large items first. With sorting, we get First Fit Decreasing and Best Fit Decreasing, as offline analogues of online First Fit and Best Fit.
C++
#include <bits/stdc++.h>
using namespace std;
int firstFitDec( int weight[], int n, int c)
{
sort(weight, weight + n, std::greater< int >());
return firstFit(weight, n, c);
}
int main()
{
int weight[] = { 2, 5, 4, 7, 1, 3, 8 };
int c = 10;
int n = sizeof (weight) / sizeof (weight[0]);
cout << "Number of bins required in First Fit "
<< "Decreasing : " << firstFitDec(weight, n, c);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int firstFitDec(Integer weight[], int n, int c)
{
Arrays.sort(weight, Collections.reverseOrder());
return firstFit(weight, n, c);
}
public static void main(String[] args)
{
Integer weight[] = { 2 , 5 , 4 , 7 , 1 , 3 , 8 };
int c = 10 ;
int n = weight.length;
System.out.print( "Number of bins required in First Fit " + "Decreasing : "
+ firstFitDec(weight, n, c));
}
}
|
Python3
def firstFit(weight, n, c):
res = 0
bin_rem = [ 0 ] * n
for i in range (n):
j = 0
while ( j < res):
if (bin_rem[j] > = weight[i]):
bin_rem[j] = bin_rem[j] - weight[i]
break
j + = 1
if (j = = res):
bin_rem[res] = c - weight[i]
res = res + 1
return res
def firstFitDec(weight, n, c):
weight.sort(reverse = True )
return firstFit(weight, n, c)
weight = [ 2 , 5 , 4 , 7 , 1 , 3 , 8 ]
c = 10
n = len (weight)
print ( "Number of bins required in First Fit Decreasing : " , str (firstFitDec(weight, n, c)))
|
C#
using System;
public class GFG
{
static int firstFitDec( int []weight, int n, int c)
{
Array.Sort(weight);
Array.Reverse(weight);
return firstFit(weight, n, c);
}
static int firstFit( int []weight, int n, int c)
{
int res = 0;
int []bin_rem = new int [n];
for ( int i = 0; i < n; i++)
{
int j;
for (j = 0; j < res; j++)
{
if (bin_rem[j] >= weight[i])
{
bin_rem[j] = bin_rem[j] - weight[i];
break ;
}
}
if (j == res)
{
bin_rem[res] = c - weight[i];
res++;
}
}
return res;
}
public static void Main(String[] args)
{
int []weight = { 2, 5, 4, 7, 1, 3, 8 };
int c = 10;
int n = weight.Length;
Console.Write( "Number of bins required in First Fit " + "Decreasing : "
+ firstFitDec(weight, n, c));
}
}
|
Javascript
function firstFit(weight, n, c) {
}
function firstFitDec(weight, n, c) {
weight.sort((a, b) => b - a);
return 3;
}
let weight = [2, 5, 4, 7, 1, 3, 8];
let c = 10;
let n = weight.length;
console.log(`Number of bins required in First Fit Decreasing: ${firstFitDec(weight, n, c)}`);
|
Output:
Number of bins required in First Fit Decreasing : 3
First Fit decreasing produces the best result for the sample input because items are sorted first.
First Fit Decreasing can also be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...