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:
Java Program to Implement Euclid GCD Algorithm
Java Program to Perform Insertion in a BST
Tiêu chuẩn coding trong Java (Coding Standards)
Spring’s RequestBody and ResponseBody Annotations
Java toString() Method
StringBuilder vs StringBuffer in Java
Spring Boot: Customize the Jackson ObjectMapper
Map to String Conversion in Java
Java Program to Implement RoleUnresolvedList API
Guide to @JsonFormat in Jackson
Java Program to Implement Shoelace Algorithm
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
JWT – Token-based Authentication trong Jersey 2.x
Period and Duration in Java
Java Program to Implement Stack using Linked List
Spring Cloud – Securing Services
Guide to java.util.concurrent.Future
Running Spring Boot Applications With Minikube
How to use the Spring FactoryBean?
Java Program to implement Associate Array
Class Loaders in Java
Simple Single Sign-On with Spring Security OAuth2
Java Streams vs Vavr Streams
Deque và ArrayDeque trong Java
Receive email using IMAP
Làm thế nào tạo instance của một class mà không gọi từ khóa new?
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Java Program to Implement LinkedHashMap API
Spring Autowiring of Generic Types
Java String to InputStream
Quick Guide to Spring Bean Scopes
Java Program to Implement Hash Tables Chaining with Binary Trees