How to resolve the algorithm Knapsack problem/Unbounded step by step in the Java programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Knapsack problem/Unbounded step by step in the Java programming language

Table of Contents

Problem Statement

A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and that the capacity of his knapsack is   0.25   'cubic lengths'. Looking just above the bar codes on the items he finds their weights and volumes.   He digs out his recent copy of a financial paper and gets the value of each item.

He can only take whole units of any item, but there is much more of any item than he could ever carry

Show how many of each item does he take to maximize the value of items he is carrying away with him.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Knapsack problem/Unbounded step by step in the Java programming language

Problem statement:

The knapsack problem is a classical optimization problem in computer science. In the unbounded knapsack problem, a set of items are given, each with a weight, value, and number of copies available. The objective is to determine the maximum total value of items one can put into a knapsack of a given capacity without exceeding the weight limit.

Java code implementation:

This Java code provides an implementation of an Unbounded Knapsack problem using a recursive approach. It efficiently calculates the maximum total value of items that can be included in a knapsack with specific weight and volume constraints while considering the available copies of each item.

Class Item:

  • The Item class models the individual items in the knapsack problem.
  • It has properties for name, value, weight, and volume.
  • It provides getter and setter methods for these properties.

Class UnboundedKnapsack:

  • The UnboundedKnapsack class represents the main logic for solving the knapsack problem.
  • It initializes the item list, the sack (knapsack), and the best solution (maximum value and weight/volume).
  • The maximum number of items (maxIt) and current item counts (iIt) are initialized for each item.
  • The calcWithRecursion method recursively calculates the best solution by iterating through the items and considering different quantities of each item.
  • It updates the best solution if a better combination is found while adhering to the weight and volume constraints.
  • Finally, it prints out the maximum achievable value, the combination of items in the best solution, and the resulting weight and volume used.

Main method:

  • The main method creates an instance of the UnboundedKnapsack class, which executes the problem-solving algorithm and prints the results.

Example usage:

Consider the sample data provided in the code:

  • Three items: "panacea," "ichor," and "gold" with their respective values, weights, and volumes.
  • A sack with a weight capacity of 25.0 and a volume capacity of 0.250.

Running the code with this data would produce output similar to:

Maximum value achievable is: 10200
This is achieved by carrying (one solution): 3 panacea, 2 ichor, 0 gold, 
The weight to carry is: 25.0  and the volume used is: 0.250

This example shows that the best solution is to include three copies of "panacea" and two copies of "ichor," yielding a total value of 10200 without exceeding the weight and volume limits of the knapsack.

Source code in the java programming language

package hu.pj.alg;

import hu.pj.obj.Item;
import java.text.*;

public class UnboundedKnapsack {

    protected Item []  items = {
                               new Item("panacea", 3000,  0.3, 0.025),
                               new Item("ichor"  , 1800,  0.2, 0.015),
                               new Item("gold"   , 2500,  2.0, 0.002)
                               };
    protected final int    n = items.length; // the number of items
    protected Item      sack = new Item("sack"   ,    0, 25.0, 0.250);
    protected Item      best = new Item("best"   ,    0,  0.0, 0.000);
    protected int  []  maxIt = new int [n];  // maximum number of items
    protected int  []    iIt = new int [n];  // current indexes of items
    protected int  [] bestAm = new int [n];  // best amounts

    public UnboundedKnapsack() {
        // initializing:
        for (int i = 0; i < n; i++) {
            maxIt [i] = Math.min(
                           (int)(sack.getWeight() / items[i].getWeight()),
                           (int)(sack.getVolume() / items[i].getVolume())
                        );
        } // for (i)

        // calc the solution:
        calcWithRecursion(0);

        // Print out the solution:
        NumberFormat nf = NumberFormat.getInstance();
        System.out.println("Maximum value achievable is: " + best.getValue());
        System.out.print("This is achieved by carrying (one solution): ");
        for (int i = 0; i < n; i++) {
            System.out.print(bestAm[i] + " " + items[i].getName() + ", ");
        }
        System.out.println();
        System.out.println("The weight to carry is: " + nf.format(best.getWeight()) +
                           "   and the volume used is: " + nf.format(best.getVolume())
                          );

    }

    // calculation the solution with recursion method
    // item : the number of item in the "items" array
    public void calcWithRecursion(int item) {
        for (int i = 0; i <= maxIt[item]; i++) {
            iIt[item] = i;
            if (item < n-1) {
                calcWithRecursion(item+1);
            } else {
                int    currVal = 0;   // current value
                double currWei = 0.0; // current weight
                double currVol = 0.0; // current Volume
                for (int j = 0; j < n; j++) {
                    currVal += iIt[j] * items[j].getValue();
                    currWei += iIt[j] * items[j].getWeight();
                    currVol += iIt[j] * items[j].getVolume();
                }

                if (currVal > best.getValue()
                    &&
                    currWei <= sack.getWeight()
                    &&
                    currVol <= sack.getVolume()
                )
                {
                    best.setValue (currVal);
                    best.setWeight(currWei);
                    best.setVolume(currVol);
                    for (int j = 0; j < n; j++) bestAm[j] = iIt[j];
                } // if (...)
            } // else
        } // for (i)
    } // calcWithRecursion()

    // the main() function:
    public static void main(String[] args) {
        new UnboundedKnapsack();
    } // main()

} // class


package hu.pj.obj;

public class Item {
    protected String name = "";
    protected int value = 0;
    protected double weight = 0;
    protected double volume = 0;

    public Item() {
    }

    public Item(String name, int value, double weight, double volume) {
        setName(name);
        setValue(value);
        setWeight(weight);
        setVolume(volume);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = Math.max(value, 0);
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = Math.max(weight, 0);
    }

    public double getVolume() {
        return volume;
    }

    public void setVolume(double volume) {
        this.volume = Math.max(volume, 0);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

} // class


  

You may also check:How to resolve the algorithm Four is magic step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Multi-dimensional array step by step in the Quackery programming language
You may also check:How to resolve the algorithm Exceptions step by step in the Ursa programming language
You may also check:How to resolve the algorithm Goldbach's comet step by step in the Perl programming language
You may also check:How to resolve the algorithm Loops/For step by step in the TUSCRIPT programming language