-1

I have been trying to figure this for over 3 days now. It is part of my fortnightly assignment for my uni. However, I have hit a road block. Any help will be must appreciated.

Specifics of the assignment, I have figured out so far:

  1. I must use an Item class that defines (get and set) the weight and value of the stuff
  2. Table arrayList holds the value and weight of
    item array stuffList
  3. Check if the maximum value stuff (Greedy) fits inside the bag's capacity and add the index of this stuff from the
    table arrayList in the bag arrayList
  4. Return bag arrayList.

The method I have written so far (Doesn't seem to be working):

Public static ArrayList <Integer> greedySelection (Item[] stuffList, int Capacity)
{
  ArrayList<Integer> bag = new ArrayList<Integer>();
  ArrayList<Integer> Table = new ArrayList<Integer>();

  for(int i = 0; i < Table.size(); i++){
   if(Table.get(i) < Capacity){
    bag.add(i);
    Table.remove(i);
   }
  }
  return bag;
}
  • hint: You create an empty list, do something for each element (there aren't any, it's still empty), then return. – Mooing Duck Nov 03 '15 at 01:27
  • Additionally, are you aware that what you have now is neither recursive nor greedy? – Mooing Duck Nov 03 '15 at 01:29
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [MCVE](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your code and accurately describe the problem. Specifically, you have not traced the execution and posted the output. If you had, you would see the basic problems. Most of all, this routine is not recursive: it doesn't call itself. – Prune Nov 04 '15 at 22:01

1 Answers1

0

Your code has several problems. You haven't focused on the basic tenet of a recursive algorithm:

  • Check to see whether you've "hit bottom".
  • If so, return the simple result.
  • If not, then do one trivial operation and recur on the remaining task.

For this routine, you need to figure out

  • When you've "hit bottom": when you can't add anything else.
  • What is the simple result at this point? Simply return the existing bag?
  • To recur, you add the most valuable item (greed) you can fit into the bag and call yourself with the new state of affairs. What is that state of affairs? At the least, you need to adjust the item list, the bag contents, and the remaining capacity.

Note that your initial state has to be set in the calling program and passed into the routine.

Does this get you moving?

Prune
  • 76,765
  • 14
  • 60
  • 81