Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced

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



ADVERTISEMENT
ADVERTISEMENT