×

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put away. It is an example of an NP-hard problem.

Example:

Arr[]={4,8,1,4,2,1}

Bin capacity=10

Output: 2

There are possibilities from the given weighted array. They are {4,4,2}, and the other possibility is {8,1,1}. Hence it is required a minimum of 2 bins is needed.

Lower Bound

There is always a minimum amount of bins that can be found. The lower bound is as follows:

A minimum number of bins >=  (Total Weight / Bin Capacity).

Applications

  • Loading trucks or containers.
  • Data storage over several discs.
  • Job planning.
  • Placing commercials during set radio/TV station breaks.
  • Putting music library on cassettes, CDs, etc

Online Algorithms

These are the Algorithms for bin packing issues, where each item must be placed in a bin before moving on to the next when it arrives one at a time (in a pending order).

1. Next Fit

Before processing the following item, ensure it will fit in the same bin as the preceding one. If it doesn't, only use a fresh bin.

Filename: BinsRequired1.java

//Java Program for finding the number of bins required using the Next fit algorithm
class BinsRequired1 {
	// The algorithm displays the number of bins required
	static int nextFits(int weights[], int num, int count)
	{
		// the result and the count of bins are initialized
		int result = 0, bin_rems = count;
		//the values are placed one after the other
		for (int i = 0; i < num; i++) {
			// checking the limit of the bin
			if (weights[i] > bin_rems) {
				result++; // Use a new bin
				bin_rems = count - weights[i];
			}
			else
				bin_rems -= weights[i];
		}
		return result;
	}
	// Main section of the Program
	public static void main(String[] args)
	{
		int weights[] = { 5, 5, 3, 7, 1, 2, 5 };
		int count = 9;
		int num = weights.length;
		System.out.println("The Number of bins required using Next Fit: " + nextFits(weights, num, count));
	}
}

Output

The Number of bins required using Next Fit: 3

Time Complexity: O(N)

Space Complexity:O(1)

Explanation

It is the easiest approach. Twice the ideal number bounds the number of bins employed by this technique, or Next Fit is about 2 in number. Take any two nearby bins as an example. Because NextFit would have moved every item from the second bin into the first if the sum of the things in these two bins were c. For every other bin, the same applies. Accordingly, if M is ideal, Next Fit uses no more than 2M bins because the maximum amount of space is wasted.

2. First Fit

Place the object in the first bin that fits while processing the following item. This is done by scanning the preceding bins in succession. Only begin a new bin if no current bins will contain it.

Filename: BinsFirstFit.java

//Program for finding the number of bins required using the First Fit Algorithm
class BinsRequired2
{
// displays the number of bins required using the First Fit Algorithm
static int firstFits(int weights[], int num, int count)
{
	// the result and the count values are initialized
	int result = 0;
	// an array is created for storing the bin values
	int []bin_rems= new int[num];
	//the item are placed one by one
	for (int i = 0; i < num; i++)
	{
		// Initial bin is identified
		int j;
		for (j = 0; j < result; j++)
		{
			if (bin_rems[j] >= weights[i])
			{
				bin_rems[j] = bin_rems[j] - weights[i];
				break;
			}
		}
		// Condition if the bin can't fit
		if (j == result)
		{
			bin_rems[result] = count - weights[i];
			result++;
		}
	}
	return result;
}
// Main section of the Program
public static void main(String[] args)
{
	int weights[] = { 1, 5, 4, 4, 1, 5, 9 };
	int count = 11;
	int num = weights.length;
	System.out.print("The Number of bins required in First Fit: "+ firstFits(weights, num, count));
}
}

Output

The Number of bins required in First Fit: 3

Time Complexity: O(N*N)

3. Best Fit

The objective is to position the following item in the *tightest* space. In other words, please place it in the trash can with the least space remaining.

Filename: BinsRequired3.java

//Program for finding the number of bins required using the Best Fit Algorithm
class BinsRequired3
{
// displays the number of bins required using the best-fit algorithm
static int bestFits(int weights[], int num, int count)
{
	// the result value is initiated
	int result = 0;
	// create an array to hold the remaining space in bins; the maximum number of bins is num.
	int []bin_rems = new int[num];
	//the items are placed after the other
	for (int i = 0; i < num; i++)
	{
		// the bin which will satisfy the condition
		int j;
		// The minimum space for bins
		int minimum = count + 1, bin = 0;
		for (j = 0; j < result; j++)
		{
			if (bin_rems[j] >= weights[i] &&
				bin_rems[j] - weights[i] < minimum)
			{
				bin = j;
				minimum = bin_rems[j] - weights[i];
			}
		}
		//If the bin does not use the value, another bin is created
		if (minimum == count + 1)
		{
			bin_rems[result] = count-weights[i];
			result++;
		}
		else 
			bin_rems[bin] -= weights[i];
	}
	return result;
}
public static void main(String[] args)
{
	int []weights = { 3, 6, 4, 5, 7, 2, 9 };
	int count = 15;
	int num = weights.length;
	System.out.print("The Bins required in Best Fit: "+ bestFits(weights, num, count));
}
}

Output

The Bins required in Best Fit: 3

Time Complexity: O(N log N)

4. Worst Fit

To balance the bins, place the estimates of the long in the least crowded area. And put it in the trash can so that most of the space is left empty.

Filename: BinsRequired4.java

///Program for finding the number of bins required using the Worst Fit Algorithm
class BinsRequired4
{
// displays the bins required in Worst Fit Algorithm
static int worstFits(int weights[], int num, int count)
{
	// the result value is initialized
	int result = 0;
	// Create an array to hold the rest of the space in bins
	//the maximum number of bins is n.
	int bin_rems[]= new int[num];
	//the items are placed one after the other
	for (int i = 0; i < num; i++)
	{
		//The bin which will accommodate the required value is selected
		int j;
		// the maximum place variable is assigned to -1
		int max = -1, win = 0;
		for (j = 0; j < result; j++) {
			if (bin_rems[j] >= weights[i] && bin_rems[j] - weights[i] > max) {
				win = j;
				max = bin_rems[j] - weights[i];
			}
		}
		// if the condition fails new bin created
		if (max == -1) {
			bin_rems[result] = count - weights[i];
			result++;
		}
		else 
			bin_rems[win] -= weights[i];
	}
	return result;
}
public static void main(String[] args)
{
	int weights[] = { 1, 2, 7, 4, 1, 2, 9 };
	int count = 10;
	int num = weights.length;
	System.out.print("The Bins Required in Worst Fit are: " +worstFits(weights, num, count));
}
}

Output

The Bins Required in Worst Fit are: 3

Time Complexity: O(N Log N)

Offline Methods

We have every element up front in the offline versions. The offline version is NP-Complete, which is unfortunate, but we have a better approximation approach. First Fit Decreasing employs a maximum of (4M + 1)/3 bins if the optimal is M.

5. First Fit Decreasing

One issue with online techniques is that packing big items can be challenging, particularly if they come up late in the sequence. We can get around this by "sorting" the input sequence and placing the bulky items at the top. Sorting produces First Fit Decreasing and Best Fit Decreasing, the offline equivalents of online First Fit and Online Best Fit.

Filename: BinsFirstFitDecreasing.java

//Program for finding the number of bins required using First Fit Decreasing
import java.util.*;
class BinsFirstFitDecreasing
{
	static int firstFits(Integer weights[], int num, int count)
        {
	// the result and the count values are initialized
	int result = 0;
	// an array is created for storing the bin values
	int []bin_rems= new int[num];
	//the item are placed one by one
	for (int i = 0; i < num; i++)
	{
		// Initial bin is identified
		int j;
		for (j = 0; j < result; j++)
		{
			if (bin_rems[j] >= weights[i])
			{
				bin_rems[j] = bin_rems[j] - weights[i];
				break;
			}
		}
		// Condition if the bin can't fit
		if (j == result)
		{
			bin_rems[result] = count - weights[i];
			result++;
		}
	}
	return result;
         }
	static int firstFitDecs(Integer weights[], int num, int count)
	{
		// The weights are arranged in sorted order
		Arrays.sort(weights, Collections.reverseOrder());
		// Now call first fit for sorted items
		return firstFits(weights, num, count);
	}
	// Main section
	public static void main(String[] args)
	{
		Integer weights[] = { 1, 3, 4, 8, 7, 5, 4};
		int count = 9;
		int num = weights.length;
		System.out.print("The Bins used in First Fit " + "Decreasing : "+ firstFitDecs(weights, num, count));
	}
}

Output

The Bins used in First Fit Decreasing: 4

Time complexity: O(N Log N)


Related Topics

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Java String lastIndexOf() method

Java String lastIndexOf() method returns last index of character or substring in a String. Syntax: Method Description int lastIndexOf(int ch)It returns last index position for the given char valueint lastIndexOf(int ch, int...

2 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.