Problem

Imagine an array of n items from which you can choose. You will place the items you choose...

Imagine an array of n items from which you can choose. You will place the items you choose into a knapsack of size k. Each item has a size and a value. Of course, you cannot take more items than you have space for in the knapsack. Your goal is to maximize the total value of the items you take.

a. Design a recursive algorithm maxKnapsack to solve this knapsack problem. The parameters to the algorithm are the knapsack, the array of items, and the position within the array of the next item to consider. The algorithm chooses the items for the knapsack and returns a knapsack containing the chosen items. A knapsack can report its size, its contents, the value of its contents, and the size of its contents. Hint: If any items in the array have not yet been considered, retrieve the next item in the array. You can either ignore the item or, if it fits, put it in the knapsack. To decide, make a recursive call for each of these two cases. Compare the knapsacks returned by these calls to see which one has the most valuable contents. Then return that knapsack.


b. Write the classes Knapsack and KnapsackItem. Then write a program that defines the method maxKnapsack. The program should read the size of the knapsack and then the size, value, and name of each available item. Here is some sample input data for a knapsack of size 10:

Size

Value

Name

1

50000

rare coin

2

7000

small gold coin

4

10000

packet of stamps

4

11000

pearl necklace

5

12000

silver bar

10

60000

painting

After displaying the items, call maxKnapsack. Then display the chosen items, their values, and their total value.

Step-by-Step Solution

Request Professional Solution

Request Solution!

We need at least 10 more requests to produce the solution.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the solution will be notified once they are available.
Add your Solution
Textbook Solutions and Answers Search
Solutions For Problems in Chapter 7
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT