×

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight restriction. As a result, we must select objects whose combined weight does not go over the allowed limit and whose combined value is as high as possible.

There are various solutions to the knapsack conundrum.

0/1 Knapsack issue

The weights and values of n different things are provided. To have the most value, these things must be placed inside a backpack with capacity k. Additionally, the knapsack's capacity k must not be exceeded by the combined weight of all the goods inside.

Exhaustive search approach

The brute force method is used in the exhaustive search Each set of items is tested in this method, and the value is calculated for each set. The solution is the set that produces the highest value.

Program for 0/1 Knapsack problem in Java

Knapsack.java

//  Exhaustive search approach for  0 - 1 Knapsack problem   
// A exhaustive search approach for the 0 - 1 Knapsack problem   
public class Knapsack 
{  
  // a method with name max is declared to find the maximum value between 2 numbers x and y
public int max(int x, int y)  
{  
// returns the maximum value
return (x > y ) ? x : y;  
}  
// Selecting the object to get maximum profit and  to fit in the bag of capacity k
public int knapSackVal(int k, int w[], int v[], int l)  
{  
// Checking whether the bag is empty 
if (l == 0 || k == 0)  
{  
    return 0;  
}  
if (w[l - 1] > k)  
{  
// usinf recursion to get maximum value
return knapSackVal(k, w, v, l - 1);  
}  
else  
{  
int v1 = knapSackVal(k - w[l - 1], w, v, l - 1);  
int v2 = knapSackVal(k, w, v, l - 1);  
return max(v[l - 1] + v1, v2);  
}  
}  
// Main method at which point of execution starts 
public static void main( String args [ ] )  
{  
 // Declaring the values of objects
int values_of_objects[] = new int [ ] { 150 , 20 , 30 } ;  
// Declaring the weights of objects
int weights_of_objects[] = new int [ ] { 30 , 20 , 40 } ;  
  
int k = 70;  
int l = values_of_objects . length ;  
Knapsack o1 = new Knapsack ( ) ;  
int ans = o1.knapSackVal ( k , weights_of_objects ,  values_of_objects , l ) ;  
System . out . println ( " The maximum value is :  "  +  ans ) ;  
}  
}  

Output

Knapsack problem in Java

Using Dynamic Programming

Dynamic programming became necessary due to how long the method above took to produce the desired outcome. The approach above so fails over time.Program for 0/1 knapsack problem using dynamic programming

 KnapsackExample.java

public class KnapsackExample 
{  
// A maximum method, which returns  the maximum of two integers num1 and num2  
public int max(int num1, int num2)  
{  
    return (num1 > num2) ? num1 : num2;  
}  
public int max_value_knapsack(int C1, int w1[], int value[], int l1)  
{  
int j1, wt1;  
int dp1[][] = new int[l1 + 1][C1 + 1];  
for (j1 = 0; j1 <= l1; j1++)  
{  
for (wt1 = 0; wt1 <= C1; wt1++)  
{  
if (j1 == 0 || wt1 == 0)  
{  
    // base case  
    dp1[j1][wt1] = 0;  
}  
else if (w1[j1 - 1] <= wt1)  
{  
    dp1[j1][wt1] = max(value[j1 - 1] + dp1[j1 - 1][wt1 - w1[j1 - 1]], dp1[j1 - 1][wt1]);  
}  
else  
{  
    dp1[j1][wt1] = dp1[j1 - 1][wt1];  
}  
}  
}  
return dp1[j1 - 1][C1];  
}  
//  Main method  
public static void main(String argvs[])  
{  
// input arrays  
// Declaring the values of objects
int ValuesOfObjects[] = new int [ ] { 200 , 150 , 100 } ;  
// Declaring the weights of objects
int WeightsOfObjects[] = new int [ ] { 130 , 20 , 40 } ;  


int C1 = 50;  
// length of the input arrays  
int l1 = ValuesOfObjects.length;  
// instantiating the class KnapsackExample  
KnapsackExample o2 = new KnapsackExample();  
// invoking the method maxValueKnapsack()  
int max_value = o2.max_value_knapsack(C1, WeightsOfObjects, ValuesOfObjects, l1);  
// displaying the final result  
System.out.println("The maximum value is: " + max_value);  
}  
}

Output

Knapsack problem in Java

Related Topics

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

How to find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.