Question

I'm having trouble with my Java Homework in which my professor wants us to solve the...

I'm having trouble with my Java Homework in which my professor wants us to solve the 0-1 Knapsack problem with Dynamic Programming. The code below is what she provided and she requested that we not change any of her existing code but simply add to it. As you can see she gave us the stub file for the knapsack class and the Item class.

You are a thief with a knapsack with a carrying capacity of knapsackCapacity pounds. You want to stuff as much value into the knapsack as possible.

There are numberOfItems of items you can pick, weights between minWeight to maxWeight and valued from minValue to maxValue. What is the list of items you will stuff into your knapsack and what is the total value?

import java.util.*;

public class Knapsack {

public static void main(String[] args) {
final int numberOfItems = 10;
final int minWeight = 1;
final int maxWeight = 5;
final int minValue = 50;
final int maxValue = 100;
final int knapsackCapacity = 20;
Item[] items = genItems(numberOfItems, minValue, maxValue, minWeight, maxWeight);

// your work here

}

static Item[] genItems(int howMany, int lValue, int hValue, int lWeight, int hWeight) {
Item[] results = new Item[howMany];
for (int i = 0; i < howMany; i++) {
int value = (int) (Math.random() * (hValue - lValue + 1)) + lValue;
int weight = (int) (Math.random() * (hWeight - lWeight + 1)) + lWeight;
results[i] = new Item("Item" + i, value, weight);
}
return results;
}

}

// My Item Class

public class Item {
String name;
int value;
int weight;

public Item(String s, int v, int w) {
name = s;
value = v;
weight = w;
}

@Override
public String toString() {
return name + ":" + value + "|" + weight;
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Item.java

public class Item {

String name;
int value;
int weight;

public Item(String s, int v, int w) {
name = s;
value = v;
weight = w;
}

@Override
public String toString() {
return name + ": " + value + " | " + weight;
}
}

Knapsack.java (Main class)

public class Knapsack {
  
public static void main(String[] args)
{
final int numberOfItems = 10;
final int minWeight = 1;
final int maxWeight = 5;
final int minValue = 50;
final int maxValue = 100;
final int knapsackCapacity = 50;
Item[] items = genItems(numberOfItems, minValue, maxValue, minWeight, maxWeight);

knapSack(knapsackCapacity, items, numberOfItems);

}

private static Item[] genItems(int howMany, int lValue, int hValue, int lWeight, int hWeight)
{
Item[] results = new Item[howMany];
for (int i = 0; i < howMany; i++)
{
int value = (int) (Math.random() * (hValue - lValue + 1)) + lValue;
int weight = (int) (Math.random() * (hWeight - lWeight + 1)) + lWeight;
results[i] = new Item("Item" + i, value, weight);
}
return results;
}
  
private static int getMax(int a, int b) { return (a > b)? a : b; }
  
private static void knapSack(int knapsackCapacity, Item items[], int numberOfItems)
{
int i, w;
int knapSack[][] = new int[numberOfItems + 1][knapsackCapacity + 1];
for(i = 0; i <= numberOfItems; i++)
{
for(w = 0; w <= knapsackCapacity; w++)
{
if(i ==0 || w == 0)
knapSack[i][w] = 0;
else if(items[i - 1].weight <= w)
knapSack[i][w] = getMax(items[i - 1].value + knapSack[i - 1][w - items[i - 1].weight], knapSack[i - 1][w]);
else
knapSack[i][w] = knapSack[i - 1][w];
}
}
  
// store the result of Knapsack
int result = knapSack[numberOfItems][knapsackCapacity];
System.out.println("Total value: " + result + "\n");
  
w = knapsackCapacity;
for(i = numberOfItems; i > 0 && result > 0; i--)
{
// either the result comes from the top
// (knapSack[i - 1][w]) or from (items[i - 1].value + K[i-1][w - items[i - 1].weight]).
// If it comes from the latter one it means the item is included in the Knapsack.
if (result == knapSack[i - 1][w])
continue;
else
{
// this item is included and so print it
System.out.println(items[i - 1].toString());
  
// As this weight is included in the Knapsack, it's value is deducted from the Knapsack table.
result = result - items[i - 1].value;
w = w - items[i - 1].weight;
}
}
}
}

******************************************************************** SCREENSHOTS *****************************************************

SAMPLE OUTPUT 1:

CD run: Total value: 817 Item9 78 2 Item8 64 | 4 Item7 93 | 3 Item6: 75 1 Item5 96 I 4 Item4: 65 3 Item3: 63 4 Item2: 93 I 4

SAMPLE OUTPUT 2:

DD run: Total value: 805 Item9 81 4 Item8 94 5 Item7 76 3 Item6: 60 5 Item5 82 3 Item4 97 | 2 Item3: 81 | 4 Item2: 74 | 5 Ite

SAMPLE OUTPUT 3:

run: DD Total value: 689 Item9 54 3 Item8 65 5 Item7 50 I 5 Item6: 74 3 Item5 88 I 2 Item4 68 I 1 Item3 55 4 Item2: 97 1 Item

**********************************************************************************************************************************************

Add a comment
Know the answer?
Add Answer to:
I'm having trouble with my Java Homework in which my professor wants us to solve the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hey guys I am having trouble getting my table to work with a java GUI if...

    Hey guys I am having trouble getting my table to work with a java GUI if anything can take a look at my code and see where I am going wrong with lines 38-49 it would be greatly appreciated! Under the JTableSortingDemo class is where I am having erorrs in my code! Thanks! :) import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import javax.swing.*; public class JTableSortingDemo extends JFrame{ private JTable table; public JTableSortingDemo(){ super("This is basic sample for your...

  • *JAVA Prompt the user for a movie name. Output the three movies that come alphabetically before...

    *JAVA Prompt the user for a movie name. Output the three movies that come alphabetically before the one entered. I need help correcting my code. I'm unsure why I am getting a name, year, and genre in my output. Input: Jericho Output: Similar title finder. Enter a movie name.\n Here are the 3 movies that are listed before the one you entered\n Jeremy Paxman Interviews...\n Jeremy Taylor\n Jeremy Vine Meets...\n Current output: Similar title finder. Enter a movie name.\n Here...

  • Java Programming Question

    After pillaging for a few weeks with our new cargo bay upgrade, we decide to branch out into a new sector of space to explore and hopefully find new targets. We travel to the next star system over, another low-security sector. After exploring the new star system for a few hours, we are hailed by a strange vessel. He sends us a message stating that he is a traveling merchant looking to purchase goods, and asks us if we would...

  • I've created a Card class and I'm asked to implement a class called DeckOfCards that stores...

    I've created a Card class and I'm asked to implement a class called DeckOfCards that stores 52 objects of the Card class. It says to include methods to shuffle the deck, deal a card, and report the number of cards left in the deck, and a toString to show the contents of the deck. The shuffle methods should assume a full deck. I also need to create a separate driver class that first outputs the populated deck to prove it...

  • I'm also having trouble on dividing the code into methods. This is my work done so...

    I'm also having trouble on dividing the code into methods. This is my work done so far and net beans give me a lot of errors. Help! package caesarcipher; import textio.TextIO; /** * * @author */ public class CaesarCipher { enum code {encodeText, decodeText }; /** * @param args the command line arguments */ public static void main(String[] args) {    String code; char x;    int totalcount = 0;    while(true){ TextIO.put("Type in an E to encode a message...

  • Below I have my 3 files. I am trying to make a dog array that aggerates...

    Below I have my 3 files. I am trying to make a dog array that aggerates with the human array. I want the users to be able to name the dogs and display the dog array but it isn't working. //Main File import java.util.*; import java.util.Scanner; public class Main {    public static void main(String[] args)    {    System.out.print("There are 5 humans.\n");    array();       }    public static String[] array()    {       //Let the user...

  • Java: Please help with my Tester. I'm having a hard time figuring out my error. Thank...

    Java: Please help with my Tester. I'm having a hard time figuring out my error. Thank you. What the tester requires: The AccountTester This class should consists of a main method that tests all the methods in each class, either directly by calling the method from the Tester or indirectly by having another method call a method. User and Bot information will be read from a file. A sample file is provided. Use this file format to aid in grading....

  • C++ PROGRAMMING Hi! My assignment prompt is below. What I'm having the most trouble understanding is...

    C++ PROGRAMMING Hi! My assignment prompt is below. What I'm having the most trouble understanding is where the shapes are being stored. I'm assuming an array, but I'm not sure how sizing would work. Any help is appreciated, thanks! I have also attached the .h file we must use. Prompt: The goal of HW2 is to implement classes representing shapes. A given program will use this class to create shapes at arbitrary locations in the x-y plane and move them....

  • Hi, I am writing Java code and I am having a trouble working it out. The...

    Hi, I am writing Java code and I am having a trouble working it out. The instructions can be found below, and the code. Thanks. Instructions Here are the methods needed for CIS425_Student: Constructor: public CIS425_Student( String id, String name, int num_exams ) Create an int array exams[num_exams] which will hold all exam grades for a student Save num_exams for later error checking public boolean addGrade( int exam, int grade ) Save a grade in the exams[ ] array at...

  • Hello I am having trouble with a connectFour java program. this issue is in my findLocalWinner...

    Hello I am having trouble with a connectFour java program. this issue is in my findLocalWinner method, it declares a winner for horizontal wins, but not for vertical. if anyone can see what im doing wrong. public class ConnectFour { /** Number of columns on the board. */ public static final int COLUMNS = 7; /** Number of rows on the board. */ public static final int ROWS = 6; /** Character for computer player's pieces */ public static final...

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
ADVERTISEMENT
ADVERTISEMENT