×

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

Maximum length of string in java

In java, String can act as a data type and a class. The string can be defined as the collection of characters that are enclosed with double quotes(“ “). The...

3 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Process and Thread in Java

Process It is a program that is running on your computer. The process is a heavy-weight, which takes memory separately to other processes. The process may be a small background task like spell-checker; it...

11 minutes read.