×

Bin Packing Problem (How to minimize the number of used Bins)

You have been given an array. The values of the array represent the size of n different items. You have been also given some bins. You have to store the items in the bins such that there will be minimum number of used bins. Maximum capacity of a bin will be given. The size of an item will not exceed the capacity of a bin.

Input- [ 2, 3, 5, 8, 13, 10, 1, 4]   capacity of the bin= 15

Output- 4

Explanation

The packing of bins are as follows:

bin1: 13, 2

bin2:  10, 1, 4

bin3:  3, 5

bin4:  8

It is possible to arrange the items between these bins in different ways. But it is obvious that we need minimum 4 bins.

Algorithm

Step 1: Start

Step 2: The size of array is taken from the user

Step 3: Values of array is taken from the user

Step 4: We sort the array

Step 5: We check the items from maximum size element.

Step 6: In this way we traverse the array and find the total count of used bins.

Step 7: Stop.

Explanation of the Algorithm

This is a NP hard problem. We sort the array first and check from maximum element after that we check if next element can be packed in the same bin or not. If not then we have to allocate one more bin. In this way we calculate the number of bins.

Code

// C++ program to find minimum number of bins to pack items

Program in 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 firstFitDec(int weight[], int n, int c)
{
	sort(weight, weight + n, std::greater<int>());
	return firstFit(weight, n, c);
}
int main()
{
	int weight[] = { 2, 3, 5, 8, 13, 10, 1, 4};
	int c = 10;
	int n = sizeof(weight) / sizeof(weight[0]);
	cout << " Total numbers of required bin: -> " << firstFitDec(weight, n, c);
	return 0;
}

//Java program to find the minimum number of bins to pack items

Program in Java

import java.util.*;
class bn
{
	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;
}
	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, 3, 5, 8, 13, 10, 1, 4};
		int c = 10;
		int n = weight.length;
		System.out.print("Total numbers of required bin: -> "
		+ firstFitDec(weight, n, c));
	}
}

# Python program to find minimum number of bins to pack items

Program in Python

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, 3, 5, 8, 13, 10, 1, 4]
c = 10
n = len(weight)
print("Total numbers of required bin: -> ",str(firstFitDec(weight, n, c)))

// C# program to find minimum number of bins to pack items

Program in C#

using System;
public class bn
{
	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, 3, 5, 8, 13, 10, 1, 4};
		int c = 10;
		int n = weight.Length;
		Console.Write("Total numbers of required bin: -> "
		+ firstFitDec(weight, n, c));
	}
}

Output: 

Total numbers of required bin:  4

Related Topics

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Find Number of Minimum Insertion to Make a String Palindrome

You have been given a string. You have to find out the number of minimum insertions to make this string palindrome. The string will contain only lower case alphabets. Note:What is...

4 minutes read.

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the...

3 minutes read.

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.

Asynchronous advantage actor-critic (A3C) Algorithm

The Asynchronous advantage actor-critic (A3C) Algorithm is one of the latest algorithms developed by the Artificial Intelligence division, Deep Mind at Google. It is used for the Deep Reinforcement Learning...

3 minutes read.

Burning binary tree

Burn the Binary tree starting from the target node You have given a binary tree and a target node value. Now you have to burn the tree from target node. You...

4 minutes read.

Pairwise swap elements of a given linked list

Pairwise swap elements of a given linked list In this problem, we have given a linked list, and we need to pairwise swap elements of the given linked list. Example:                                     Input:1 ->3...

4 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

4 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

Program to calculate the area of the circumcircle of an equilateral triangle

You have given one value which represents the side of the equilateral triangle. You have to find out the area of the circumcircle. Let’s take an example - For the above...

3 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Difference Between Linear and Non Linear Data Structures

Data Structure A data structure is a data object together with the relationships between the instances and the individual elements that compose an instance. These relationships are defined by the operations...

5 minutes read.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

4 minutes read.

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

FLEX (Fast Lexical Analyzer Generator)

FLEX stands for Fast Lexical Analyzer Generator. Around 1987, Vern Paxson created Flex in C with a great deal of input and inspiration from Van Jacobson. Van Jacobson's approach is...

3 minutes read.

About Data Structures

What exactly are data structures? A data structure is a type of storage that is used to organise and store data. It is a method of organising data on a computer...

5 minutes read.