Bin Packing Problem (Minimize number of used Bins)
Last Updated :
02 Dec, 2024
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.
Examples:
Input: weight[] = [4, 8, 1, 4, 2, 1], c = 10
Output: 2
Explanation: 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], c = 10
Output: 4
Explanation: We need minimum 4 bins to accommodate all items.
Input: weight[] = [2, 5, 4, 7, 1, 3, 8], c = 10
Output: 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.
Lower Bound
We can always find a lower bound on minimum number of bins required 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.
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++
// C++ program to find number of bins required using
// next fit algorithm.
#include <bits/stdc++.h>
using namespace std;
// Returns number of bins required using next fit
// online algorithm
int nextFit(int weight[], int n, int c)
{
// Initialize result (Count of bins) and remaining
// capacity in current bin.
int res = 0, bin_rem = c;
// Place items one by one
for (int i = 0; i < n; i++) {
// If this item can't fit in current bin
if (weight[i] > bin_rem) {
res++; // Use a new bin
bin_rem = c - weight[i];
}
else
bin_rem -= weight[i];
}
return res;
}
// Driver program
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
// Java program to find number
// of bins required using
// next fit algorithm.
class GFG {
// Returns number of bins required
// using next fit online algorithm
static int nextFit(int weight[], int n, int c)
{
// Initialize result (Count of bins) and remaining
// capacity in current bin.
int res = 0, bin_rem = c;
// Place items one by one
for (int i = 0; i < n; i++) {
// If this item can't fit in current bin
if (weight[i] > bin_rem) {
res++; // Use a new bin
bin_rem = c - weight[i];
}
else
bin_rem -= weight[i];
}
return res;
}
// Driver program
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));
}
}
// This code has been contributed by 29AjayKumar
Python
# Python3 implementation for above approach
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
# Driver Code
weight = [2, 5, 4, 7, 1, 3, 8]
c = 10
print("Number of bins required in Next Fit :",
nextfit(weight, c))
# This code is contributed by code_freak
C#
// C# program to find number
// of bins required using
// next fit algorithm.
using System;
class GFG
{
// Returns number of bins required
// using next fit online algorithm
static int nextFit(int []weight, int n, int c)
{
// Initialize result (Count of bins) and remaining
// capacity in current bin.
int res = 0, bin_rem = c;
// Place items one by one
for (int i = 0; i < n; i++)
{
// If this item can't fit in current bin
if (weight[i] > bin_rem)
{
res++; // Use a new bin
bin_rem = c - weight[i];
}
else
bin_rem -= weight[i];
}
return res;
}
// Driver program
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));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// JavaScript program to find number
// of bins required using
// next fit algorithm.
// Returns number of bins required
// using next fit online algorithm
function nextFit(weight, n, c)
{
// Initialize result (Count of bins) and remaining
// capacity in current bin.
let res = 0, bin_rem = c;
// Place items one by one
for (let i = 0; i < n; i++)
{
// If this item can't fit in current bin
if (weight[i] > bin_rem)
{
res++; // Use a new bin
bin_rem = c - weight[i];
}
else
bin_rem -= weight[i];
}
return res;
}
// Driver Code
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));
// This code is contributed by target_2.
</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++
// C++ program to find number of bins required using
// First Fit algorithm.
#include <bits/stdc++.h>
using namespace std;
// Returns number of bins required using first fit
// online algorithm
int firstFit(int weight[], int n, int c)
{
// Initialize result (Count of bins)
int res = 0;
// Create an array to store remaining space in bins
// there can be at most n bins
int bin_rem[n];
// Place items one by one
for (int i = 0; i < n; i++) {
// Find the first bin that can accommodate
// weight[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 no bin could accommodate weight[i]
if (j == res) {
bin_rem[res] = c - weight[i];
res++;
}
}
return res;
}
// Driver program
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
// Java program to find number of bins required using
// First Fit algorithm.
class GFG
{
// Returns number of bins required using first fit
// online algorithm
static int firstFit(int weight[], int n, int c)
{
// Initialize result (Count of bins)
int res = 0;
// Create an array to store remaining space in bins
// there can be at most n bins
int []bin_rem = new int[n];
// Place items one by one
for (int i = 0; i < n; i++)
{
// Find the first bin that can accommodate
// weight[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 no bin could accommodate weight[i]
if (j == res)
{
bin_rem[res] = c - weight[i];
res++;
}
}
return res;
}
// Driver program
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));
}
}
// This code is contributed by Rajput-Ji
Python
# Python program to find number of bins required using
# First Fit algorithm.
# Returns number of bins required using first fit
# online algorithm
def firstFit(weight, n, c):
# Initialize result (Count of bins)
res = 0
# Create an array to store remaining space in bins
# there can be at most n bins
bin_rem = [0]*n
# Place items one by one
for i in range(n):
# Find the first bin that can accommodate
# weight[i]
j = 0
while( j < res):
if (bin_rem[j] >= weight[i]):
bin_rem[j] = bin_rem[j] - weight[i]
break
j+=1
# If no bin could accommodate weight[i]
if (j == res):
bin_rem[res] = c - weight[i]
res= res+1
return res
# Driver program
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))
# This code is contributed by shubhamsingh10
C#
// C# program to find number of bins required using
// First Fit algorithm.
using System;
class GFG
{
// Returns number of bins required using first fit
// online algorithm
static int firstFit(int []weight, int n, int c)
{
// Initialize result (Count of bins)
int res = 0;
// Create an array to store remaining space in bins
// there can be at most n bins
int []bin_rem = new int[n];
// Place items one by one
for (int i = 0; i < n; i++)
{
// Find the first bin that can accommodate
// weight[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 no bin could accommodate weight[i]
if (j == res)
{
bin_rem[res] = c - weight[i];
res++;
}
}
return res;
}
// Driver code
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));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to find number of bins required using
// First Fit algorithm.
// Returns number of bins required using first fit
// online algorithm
function firstFit(weight,n,c)
{
// Initialize result (Count of bins)
let res = 0;
// Create an array to store remaining space in bins
// there can be at most n bins
let bin_rem = new Array(n);
// Place items one by one
for (let i = 0; i < n; i++)
{
// Find the first bin that can accommodate
// weight[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 no bin could accommodate weight[i]
if (j == res)
{
bin_rem[res] = c - weight[i];
res++;
}
}
return res;
}
// Driver program
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));
// This code is contributed by patel2127
</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++
// C++ program to find number
// of bins required using
// Best fit algorithm.
#include <bits/stdc++.h>
using namespace std;
// Returns number of bins required using best fit
// online algorithm
int bestFit(int weight[], int n, int c)
{
// Initialize result (Count of bins)
int res = 0;
// Create an array to store
// remaining space in bins
// there can be at most n bins
int bin_rem[n];
// Place items one by one
for (int i = 0; i < n; i++) {
// Find the best bin that can accommodate
// weight[i]
int j;
// Initialize minimum space left and index
// of best bin
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 no bin could accommodate weight[i],
// create a new bin
if (min == c + 1) {
bin_rem[res] = c - weight[i];
res++;
}
else // Assign the item to best bin
bin_rem[bi] -= weight[i];
}
return res;
}
// Driver program
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
// Java program to find number
// of bins required using
// Best fit algorithm.
class GFG
{
// Returns number of bins
// required using best fit
// online algorithm
static int bestFit(int weight[], int n, int c)
{
// Initialize result (Count of bins)
int res = 0;
// Create an array to store
// remaining space in bins
// there can be at most n bins
int []bin_rem = new int[n];
// Place items one by one
for (int i = 0; i < n; i++)
{
// Find the best bin that
// can accommodate
// weight[i]
int j;
// Initialize minimum space
// left and index
// of best bin
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 no bin could accommodate weight[i],
// create a new bin
if (min == c + 1)
{
bin_rem[res] = c - weight[i];
res++;
}
else // Assign the item to best bin
bin_rem[bi] -= weight[i];
}
return res;
}
// Driver code
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));
}
}
// This code is contributed by 29AjayKumar
Python
# Python3 program to find number
# of bins required using
# First Fit algorithm.
# Returns number of bins required
# using first fit
# online algorithm
def firstFit(weight, n, c):
# Initialize result (Count of bins)
res = 0;
# Create an array to store
# remaining space in bins
# there can be at most n bins
bin_rem = [0]*n;
# Place items one by one
for i in range(n):
# Find the first bin that
# can accommodate
# weight[i]
j = 0;
# Initialize minimum space
# left and index
# of best bin
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 no bin could accommodate weight[i],
# create a new bin
if (min == c + 1):
bin_rem[res] = c - weight[i];
res += 1;
else: # Assign the item to best bin
bin_rem[bi] -= weight[i];
return res;
# Driver code
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));
# This code is contributed by Rajput-Ji
C#
// C# program to find number
// of bins required using
// Best fit algorithm.
using System;
class GFG {
// Returns number of bins
// required using best fit
// online algorithm
static int bestFit(int[] weight, int n, int c)
{
// Initialize result (Count of bins)
int res = 0;
// Create an array to store
// remaining space in bins
// there can be at most n bins
int[] bin_rem = new int[n];
// Place items one by one
for (int i = 0; i < n; i++) {
// Find the best bin that
// can accommodate
// weight[i]
int j;
// Initialize minimum space
// left and index
// of best bin
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 no bin could accommodate weight[i],
// create a new bin
if (min == c + 1) {
bin_rem[res] = c - weight[i];
res++;
}
// Assign the item to best bin
else
bin_rem[bi] -= weight[i];
}
return res;
}
// Driver code
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));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// javascript program to find number
// of bins required using
// Best fit algorithm.
// Returns number of bins
// required using best fit
// online algorithm
function bestFit(weight , n , c) {
// Initialize result (Count of bins)
var res = 0;
// Create an array to store
// remaining space in bins
// there can be at most n bins
var bin_rem = Array(n).fill(0);
// Place items one by one
for (i = 0; i < n; i++) {
// Find the best bin that
// can accommodate
// weight[i]
var j;
// Initialize minimum space
// left and index
// of best bin
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 no bin could accommodate weight[i],
// create a new bin
if (min == c + 1) {
bin_rem[res] = c - weight[i];
res++;
} else // Assign the item to best bin
bin_rem[bi] -= weight[i];
}
return res;
}
// Driver code
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));
// This code contributed by gauravrajput1
</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++
// C++ program to find number of bins required using
// Worst fit algorithm.
#include <bits/stdc++.h>
using namespace std;
// Returns number of bins required using worst fit
// online algorithm
int worstFit(int weight[], int n, int c)
{
// Initialize result (Count of bins)
int res = 0;
// Create an array to store remaining space in bins
// there can be at most n bins
int bin_rem[n];
// Place items one by one
for (int i = 0; i < n; i++) {
// Find the best bin that can accommodate
// weight[i]
int j;
// Initialize maximum space left and index
// of worst bin
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 no bin could accommodate weight[i],
// create a new bin
if (mx == -1) {
bin_rem[res] = c - weight[i];
res++;
}
else // Assign the item to best bin
bin_rem[wi] -= weight[i];
}
return res;
}
// Driver program
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;
}
// This code is contributed by gromperen
Java
// Java program to find number of bins required using
// Worst fit algorithm.
class GFG
{
// Returns number of bins required using worst fit
// online algorithm
static int worstFit(int weight[], int n, int c)
{
// Initialize result (Count of bins)
int res = 0;
// Create an array to store remaining space in bins
// there can be at most n bins
int bin_rem[]= new int[n];
// Place items one by one
for (int i = 0; i < n; i++)
{
// Find the best bin that can accommodate
// weight[i]
int j;
// Initialize maximum space left and index
// of worst bin
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 no bin could accommodate weight[i],
// create a new bin
if (mx == -1) {
bin_rem[res] = c - weight[i];
res++;
}
else // Assign the item to best bin
bin_rem[wi] -= weight[i];
}
return res;
}
// Driver program
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));
}
}
// This code is contributed by shivanisinghss2110
Python
# Python program to find number of bins required using# Worst fit algorithm.# Returns number of bins required using worst fit# online algorithm
def worstFit( weight, n, c):
# Initialize result (Count of bins)
res = 0
# Create an array to store remaining space in bins
# there can be at most n bins
bin_rem = [0 for i in range(n)]
# Place items one by one
for i in range(n):
# Find the best bin that can accommodate
# weight[i]
# Initialize maximum space left and index
# of worst bin
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 no bin could accommodate weight[i],
# create a new bin
if (mx == -1):
bin_rem[res] = c - weight[i]
res += 1
else: # Assign the item to best bin
bin_rem[wi] -= weight[i]
return res
# Driver program
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)}")
# This code is contributed by shinjanpatra
C#
// C# program to find number of bins required using
// Worst fit algorithm.
using System;
class GFG
{
// Returns number of bins required using worst fit
// online algorithm
static int worstFit(int []weight, int n, int c)
{
// Initialize result (Count of bins)
int res = 0;
// Create an array to store remaining space in bins
// there can be at most n bins
int []bin_rem= new int[n];
// Place items one by one
for (int i = 0; i < n; i++)
{
// Find the best bin that can accommodate
// weight[i]
int j;
// Initialize maximum space left and index
// of worst bin
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 no bin could accommodate weight[i],
// create a new bin
if (mx == -1) {
bin_rem[res] = c - weight[i];
res++;
}
else // Assign the item to best bin
bin_rem[wi] -= weight[i];
}
return res;
}
// Driver program
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));
}
}
// This code is contributed by shivanisinghss2110
JavaScript
<script>
// javascript program to find number of bins required using
// Worst fit algorithm.
// Returns number of bins required using worst fit
// online algorithm
function worstFit( weight, n, c)
{
// Initialize result (Count of bins)
var res = 0;
// Create an array to store remaining space in bins
// there can be at most n bins
var bin_rem = Array(n).fill(0);
// Place items one by one
for (var i = 0; i < n; i++)
{
// Find the best bin that can accommodate
// weight[i]
var j;
// Initialize maximum space left and index
// of worst bin
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 no bin could accommodate weight[i],
// create a new bin
if (mx == -1) {
bin_rem[res] = c - weight[i];
res++;
}
else // Assign the item to best bin
bin_rem[wi] -= weight[i];
}
return res;
}
// Driver program
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));
// This code is contributed by shivanisinghss2110
</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.
1. 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++
// C++ program to find number of bins required using
// First Fit Decreasing algorithm.
#include <bits/stdc++.h>
using namespace std;
/* Copy firstFit() from above */
// Returns number of bins required using first fit
// decreasing offline algorithm
int firstFitDec(int weight[], int n, int c)
{
// First sort all weights in decreasing order
sort(weight, weight + n, std::greater<int>());
// Now call first fit for sorted items
return firstFit(weight, n, c);
}
// Driver program
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
// Java program to find number of bins required using
// First Fit Decreasing algorithm.
import java.util.*;
class GFG
{
/* Copy firstFit() from above */
// Returns number of bins required using first fit
// decreasing offline algorithm
static int firstFitDec(Integer weight[], int n, int c)
{
// First sort all weights in decreasing order
Arrays.sort(weight, Collections.reverseOrder());
// Now call first fit for sorted items
return firstFit(weight, n, c);
}
// Driver code
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));
}
}
// This code is contributed by Rajput-Ji
Python
# Python program to find number of bins required using
# First Fit Decreasing algorithm.
# Returns number of bins required using first fit
# online algorithm
def firstFit(weight, n, c):
# Initialize result (Count of bins)
res = 0
# Create an array to store remaining space in bins
# there can be at most n bins
bin_rem = [0]*n
# Place items one by one
for i in range(n):
# Find the first bin that can accommodate
# weight[i]
j = 0
while( j < res):
if (bin_rem[j] >= weight[i]):
bin_rem[j] = bin_rem[j] - weight[i]
break
j+=1
# If no bin could accommodate weight[i]
if (j == res):
bin_rem[res] = c - weight[i]
res= res+1
return res
# Returns number of bins required using first fit
# decreasing offline algorithm
def firstFitDec(weight, n, c):
# First sort all weights in decreasing order
weight.sort(reverse = True)
# Now call first fit for sorted items
return firstFit(weight, n, c)
# Driver program
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)))
# This code is contributed by shinjanpatra
C#
// C# program to find number of bins required using
// First Fit Decreasing algorithm.
using System;
public class GFG
{
/* Copy firstFit() from above */
// Returns number of bins required using first fit
// decreasing offline algorithm
static int firstFitDec(int []weight, int n, int c)
{
// First sort all weights in decreasing order
Array.Sort(weight);
Array.Reverse(weight);
// Now call first fit for sorted items
return firstFit(weight, n, c);
}
static int firstFit(int []weight, int n, int c)
{
// Initialize result (Count of bins)
int res = 0;
// Create an array to store remaining space in bins
// there can be at most n bins
int []bin_rem = new int[n];
// Place items one by one
for (int i = 0; i < n; i++)
{
// Find the first bin that can accommodate
// weight[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 no bin could accommodate weight[i]
if (j == res)
{
bin_rem[res] = c - weight[i];
res++;
}
}
return res;
}
// Driver code
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));
}
}
// This code is contributed by 29AjayKumar
JavaScript
function firstFit(weight, n, c) {
// Implement firstFit() function here
}
function firstFitDec(weight, n, c) {
// Sort all weights in decreasing order
weight.sort((a, b) => b - a);
// Now call firstFit() for sorted items
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)}`);
// This code is contributed by ishankhandelwals.
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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem