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 Cartesian Tree
The Modulo Operator in Java
Spring Boot - Rest Template
Java Program to Find Transitive Closure of a Graph
Create Java Applet to Simulate Any Sorting Technique
Spring Boot - Interceptor
Spring Boot - Zuul Proxy Server and Routing
A Guide to Queries in Spring Data MongoDB
Working with Tree Model Nodes in Jackson
A Guide to EnumMap
Lớp lồng nhau trong java (Java inner class)
Java Program to Implement HashTable API
Spring Boot - Securing Web Applications
Java Program to Implement Shell Sort
HashMap trong Java hoạt động như thế nào?
HttpClient with SSL
Using Spring ResponseEntity to Manipulate the HTTP Response
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
A Guide to LinkedHashMap in Java
Hướng dẫn Java Design Pattern – Dependency Injection
Giới thiệu java.io.tmpdir
Giới thiệu Google Guice – Injection, Scope
Java Program to Construct an Expression Tree for an Infix Expression
LinkedHashSet trong Java hoạt động như thế nào?
Spring Boot: Customize the Jackson ObjectMapper
New Features in Java 10
Sử dụng Fork/Join Framework với ForkJoinPool trong Java
Java Program to Check Cycle in a Graph using Topological Sort
Java 8 Streams peek() API
Limiting Query Results with JPA and Spring Data JPA
Java Program to Implement a Binary Search Tree using Linked Lists
Remove All Occurrences of a Specific Value from a List