×

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

Why is Binary Heap Preferred over BST for Priority Queue

A priority queue is a linear and ordered collection of elements in which each element has an attribute named priority and the priority attribute decides the order in which elements...

2 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Circular Linked List

Circular Linked List A circular linked list where all nodes are connected to their next node and last node is connected to the starting node or we can say all nodes...

5 minutes read.

Segregate Even and Odd nodes in a Linked List

Segregate even and odd nodes in a Linked List In this problem, we have given a linked list with integer numbers. We need to modify the given linked list in such...

4 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

Delete nodes from the linked list which have a greater value on the right side

Delete nodes from the linked list which have a greater value on the right side In this problem, we have given a singly linked list, and we need to remove all...

3 minutes read.

Counts the number of times a given element occurs in a Linked List

Counts the number of times a given element occurs in a Linked List This article will explain how we can count the occurrences of a particular element in a list. Here,...

3 minutes read.

Invert binary tree

Invert binary tree is a mirror image of a tree. It is pretty much the same compared to the only difference: its left and right children are swapped with the...

4 minutes read.

Heap Data Structure

In this article, we will learn in detail about Heap (Min heap and Max heap). Before going to the main topics, let’s have a look at what is complete binary...

19 minutes read.

Asymptotic Notation

Asymptotic notation is expressions that are used to represent the complexity of algorithms. The complexity of the algorithm is analyzed from two perspectives:  Time complexitySpace complexity Time complexity The time complexity of an algorithm is the...

3 minutes read.

Flatten Binary Tree to a linked list

Implementation In this section, we will see the implementation of the binary Tree and its conversion into linked lists. let us proceed: - // Writing a C++ program that will convert a...

4 minutes read.

Berkley’s Algorithm

Berkley’s Algorithm is mainly used in clock synchronization system. It is used in distributed systems. To implement this algorithm, we have to think that the network has no accurate time...

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.

Flattening a Linked List

In this article, we are going to study about the logic behind the flattening of linked list and we also going to build a code in the C++ to flatten...

3 minutes read.

Winner tree in Data Structures

Tree Data structure A tree is a hierarchical and non-linear data structure with nodes. Each node in the Tree contains a message value and stores the name passed to another ("child")...

6 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.

Given a Binary Tree Print the Shortest Path

Implementation // Writing a program in C++ to find the shortest between the nodes i and j.  #include <bits/stdc++.h> using namespace std; // the given function will print the path between nodes i and...

7 minutes read.

Count pairs from two linked lists whose sum is equal to a given value

Count pairs from two linked lists whose sum is equal to a given value In this problem, we have given two linked lists of size n1 and n2 with distinct elements...

4 minutes read.

Bucket Sort

Bucket Sort: In the sorting algorithm, we create buckets and put elements into them. We can apply some sorting algorithm (insertion sort) to sort the elements in each bucket. Finally,...

4 minutes read.

Write Main Difference Between Tree and Graph in Data Structures

Graph: The graph has two sets, which are considered V and E. These vertices are also called nodes, and edges are referred to as arcs connecting any two nodes in a...

4 minutes read.