Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

knapsack problem

843785Mar 10 2009 — edited Mar 11 2009
Hey everyone,

I am working on writing a program that solves the knapsack problem. I have an array of weights in a class I called "Sack". I am trying to make a recursive method which tries to insert weights into a new array until the target weight has been met. The problem I have having is how I am going to keep track of things. A hint was given to me that for the recursive knapsack funtion, the target weight and the array index of where the remaining items start are the arguments. How can I keep track of what is being tested aritrarily? Any help would be greatly appreciated, and this is what I have so far for my Stack class
public class Sack 
{

		private int[] aSack, weights;
		private int weightTarget;
		private int weightIndex;
		
		public Sack(int n, int j)
		{
			aSack = new int[n];		//creates a sack with capacity n.
			weights = new int[j];
			weightIndex = 0;
		}
		
		public void addWeights(int x)
		{
			if(weightIndex != weights.length)
			{
				weights[weightIndex] = x;
				weightIndex++;
			}
		}
		
		
		public void setTargetWeight(int n)
		{
			weightTarget = n;			//sets sack target weight
		}
		
		
		public void knapSack(int index, int target)
		{
			
			
		}
		
		
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 8 2009
Added on Mar 10 2009
7 comments
210 views