This is the java implementation of classic Bin-Packing algorithm. In the bin packing problem, objects of different volumes must be packed into a finite number of bins or containers each of volume V in a way that minimizes the number of bins used. In computational complexity theory, it is a combinatorial NP-hard problem.
Here is the source code of the Java Program to Implement the Bin Packing Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
//This is a sample program to illustrate the Bin-Packing algorithm using next fit heuristics
import java.util.Scanner;
public class Bin_Packing_Algorithm
{
public static void binPacking(int []a, int size, int n)
{
int binCount=1;
int s = size;
for(int i=0; i<n; i++)
{
if(s - a[i] > 0)
{
s -= a[i];
continue;
}
else
{
binCount++;
s = size;
i--;
}
}
System.out.println("Number of bins required: "+binCount);
}
public static void main(String args[])
{
System.out.println("BIN - PACKING Algorithm");
System.out.println("Enter the number of items in Set: ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("Enter "+n+" items:");
int []a = new int[n];
for(int i=0; i<n; i++)
a[i] = sc.nextInt();
System.out.println("Enter the bin size: ");
int size = sc.nextInt();
binPacking(a, size, n);
sc.close();
}
}
Output:
$ javac Bin_Packing_Algorithm.java $ java Bin_Packing_Algorithm BIN - PACKING Algorithm Enter the number of items in Set: 8 Enter 8 items: 4 5 8 3 4 5 1 6 Enter the bin size: 10 Number of bins required: 5
Related posts:
Testing in Spring Boot
Rate Limiting in Spring Cloud Netflix Zuul
Guide to @ConfigurationProperties in Spring Boot
A Guide to Java HashMap
Java Program to Perform Addition Operation Using Bitwise Operators
Guide to BufferedReader
Java Program to Find kth Smallest Element by the Method of Partitioning the Array
A Guide to JUnit 5
Count Occurrences of a Char in a String
Java Program to Perform Arithmetic Operations on Numbers of Size
Tránh lỗi NullPointerException trong Java như thế nào?
Exploring the New Spring Cloud Gateway
Guide to System.gc()
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
Java Program to Implement a Binary Search Tree using Linked Lists
Spring Data MongoDB Transactions
JUnit5 @RunWith
Java Program to Find the Vertex Connectivity of a Graph
Java Program to Implement Sorted Doubly Linked List
How to Convert List to Map in Java
Java Program to Implement Sorted List
Java – Convert File to InputStream
Java Program to Implement Gauss Jordan Elimination
HttpClient Timeout
Logout in an OAuth Secured Application
Introduction to Spring MVC HandlerInterceptor
Java Program to Implement Regular Falsi Algorithm
Java Program to Check whether Undirected Graph is Connected using DFS
Custom Cascading in Spring Data MongoDB
Spring Boot Configuration with Jasypt
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
LinkedHashSet trong Java hoạt động như thế nào?