Question

In: Computer Science

Consider the knapsack problem with the capacity C = 8 and 5 items with weights 6,...

  1. Consider the knapsack problem with the capacity C = 8 and 5 items with weights 6, 4, 3, 7, 1. Find which items will exactly fill the knapsack using dynamic programming solution introduced in class. Show all your work. use I/O knapsack

Solutions

Expert Solution

Answer:

There has to be some values (prices as such) of the given items. I have given some random values of the items to solve the knapsack problem.

Code:

import java.util.ArrayList;

import java.util.List;

class Item {

    public String name;

    public int value;

    public int weight;

    public Item(String name,int value,int weight){

        this.name=name;

        this.value=value;

        this.weight=weight;

    }

    public String str(){

        return name + "[value = " + value  + ", weight = " + weight + "]";

    }

}

class Solution{

    public List<Item> items;

    public int value;

    public Solution(List<Item> items,int value){

        this.items=items;

        this.value=value;

    }

    public void display(){

        if(items!=null && !items.isEmpty()){

            System.out.println("\n Knapsack problem");

            System.out.println("Value: "+value);

            System.out.println("Items to pick:");

            for(Item item:items){

                System.out.println("- "+item.str());

            }

        }

    }

}

public class Knapsack{

    private Item[] items;

    private int capacity;

    public Knapsack(Item[] items,int capacity){

        this.items=items;

        this.capacity=capacity;

    }

    public void display(){

        if(items!=null && items.length>0){

            System.out.println("Knapsack problem");

            System.out.println("Capacity: "+capacity);

            System.out.println("Items:");

            for(Item item:items){

                System.out.println("- "+item.str());

            }

        }

    }

    public Solution solve(){

        int NB_ITEMS=items.length;

        int[][] matrix=new int[NB_ITEMS+1][capacity+1];

        for(int i=0;i<=capacity;i++)

            matrix[0][i]=0;

        for(int i=1;i<=NB_ITEMS;i++){

            for(int j=0;j<=capacity;j++){

                if(items[i-1].weight>j){

                    matrix[i][j]=matrix[i-1][j];

                }

                else{

                    matrix[i][j]=Math.max(matrix[i-1][j],matrix[i-1][j-items[i-1].weight]+items[i-1].value);

                }

            }

        }

        int res=matrix[NB_ITEMS][capacity];

        int w=capacity;

        List<Item> itemsSolution=new ArrayList<>();

        for(int i=NB_ITEMS;i>0 && res>0;i--){

            if(res!=matrix[i-1][w]){

                itemsSolution.add(items[i-1]);

                res-=items[i-1].value;

                w-=items[i-1].weight;

            }

        }

        return new Solution(itemsSolution,matrix[NB_ITEMS][capacity]);

    }

    public static void main(String[] args){

        Item[] items={new Item("Elt1",4,6),new Item("Elt2",2,4),new Item("Elt3",2,3),new Item("Elt4",1,7),new Item("Elt5",10,1)};

        Knapsack knapsack=new Knapsack(items,8);

        knapsack.display();

        Solution solution=knapsack.solve();

        solution.display();

    }

}

Output:


Related Solutions

Consider the following items in the Knapsack Problem: Item                weight             value &nbsp
Consider the following items in the Knapsack Problem: Item                weight             value            Knapsack capacity W = 9. 1                      3                   $6 2 4 $12 3                      2                  $10 4                      5                  $20 Determine the maximum value in the knapsack if we allow repetitions; i.e., if there are an unlimited number of each item so that more than one such item can be chosen. Find the missing value in the following linear array. P(w) is the maximum profit obtainable for a knapsack of capacity w. w-->             0       1      2       3       4       5       6       7       8       9 P(w):    0 0 10 10     20     20     30    30 40 ?   P(9)...
Knapsack algorithm problem: Consider the following variation of the Knapsack problem. There are n types of...
Knapsack algorithm problem: Consider the following variation of the Knapsack problem. There are n types of items, let call them 1,2,3,4,...,n. There are exactly c_i copies of item i, and each such copy has value v_i and weight w_i. As before, the knapsack capacity is W, and the other constraint is that you can only take at most c_i copies of item i ( since no more are available). Show how to compute the optimal value that can be achieved...
Fractional Knapsack Problem Algorithm which best describes the tightest range of the number of items with...
Fractional Knapsack Problem Algorithm which best describes the tightest range of the number of items with only fractional inclusion (i.e. not entirely included or excluded) in the knapsack? (Let n denote the number of items for possible inclusion.) A) At least 0 items and at most n items B) At least 1 items and at most n items C) Exactly n items D) At least 0 items and at most n-1 items E) At least 1 items and at most...
There are many variations on the Knapsack problem. In this question, consider the same set up...
There are many variations on the Knapsack problem. In this question, consider the same set up as the 0-1 Knapsack problem except suppose there are as many copies of each item as you would like. Thus, if one of the items is small but very valuable, it is possible to put many exact duplicates of that item into the knapsack. To maximize the value of items in the knapsack, the thief may decide to put in as many of the...
In C++ or Java Write the Greedy programming Algorithm for the 0-1 Knapsack problem.                    (a)...
In C++ or Java Write the Greedy programming Algorithm for the 0-1 Knapsack problem.                    (a) No fraction allowed Max Weight W= 9 item 1: profit $20, weight 2, prof/weight=$10 item 2: profit $30, weight 5, prof/weight=$6 item 3: profit $35, weight 7, prof/weight=$5 item 4: profit $12, weight 3, prof/weight=$4 item 5: profit $3, weight 1, prof/weight=$3
Consider the following. n = 8 measurements: 4, 3, 7, 8, 5, 6, 4, 6 Calculate...
Consider the following. n = 8 measurements: 4, 3, 7, 8, 5, 6, 4, 6 Calculate the sample variance, s2, using the definition formula. (Round your answer to four decimal places.) s2 = Calculate the sample variance, s2 using the computing formula. (Round your answer to four decimal places.) s2 = Find the sample standard deviation, s. (Round your answer to three decimal places.) s =
6)Consider the following voting problem: there are 3 alternatives A, B, and C. There are 3...
6)Consider the following voting problem: there are 3 alternatives A, B, and C. There are 3 voters whose preferences are as follows: Voter 1: A > B > C Voter 2: B > C > A Voter 3: C > A > B The voting procedure is as follows: first A competes with B and then the winner competes with C. If voters are strategic what is the voting outcome? Who will each voter vote for in the first stage?
Lawyer Nurse Teacher Control 8 6 9 8 5 7 6 7 7 6 8 6...
Lawyer Nurse Teacher Control 8 6 9 8 5 7 6 7 7 6 8 6 7 8 8 7 4 9 7 9 A researcher is interested in whether the likeability of a crying woman is affected by the viewer’s knowledge of the woman’s occupation. Twenty participants were shown a video of a woman crying and were asked to rate her likeability on a scale from 1 (not very likable) to 10 (highly likable). Prior to viewing the video,...
Problem 6-34 (Algorithmic) (LO. 5, 6, 8) Five years ago, Gerald invested $186,000 in a passive...
Problem 6-34 (Algorithmic) (LO. 5, 6, 8) Five years ago, Gerald invested $186,000 in a passive activity, his sole investment venture. On January 1, 2017, his amount at risk in the activity was $37,200. His shares of the income and losses were as follows: Year Income (Loss) 2017 ($55,800) 2018 (37,200) 2019 57,200 Gerald holds no suspended at-risk or passive activity losses at the beginning of 2017. If an answer is zero, enter "0". a. If losses were limited only...
Consider the paired sample {(3, 1),(3, 5),(6, 6),(6, 8),(7, 10)}. Do the following by hand (you...
Consider the paired sample {(3, 1),(3, 5),(6, 6),(6, 8),(7, 10)}. Do the following by hand (you may use a basic calculator, but not a statistical program). (a) Find estimates βˆ 0 and βˆ 1 of the regression parameters β0 and β1. (b) Make a rough sketch of the data and regression line. (c) Predict the value of y when x = 5. (d) Predict the value of y when x = 15. (e) Which prediction (part c or d) do...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT