jake
Posts: 83
Nickname: onorok
Registered: May, 2002
|
|
Re: KnapSack problem
|
Posted: May 16, 2003 3:17 AM
|
|
Here is what I have so far:
public class Sack
{
int[] sArray;
/**********************************************************
Name: Sack
Parameters: five integers
Declared variables: none
Return value: constructor
Purpose:
Creates a new array and inserts the five parameters into
the array.
**********************************************************/
public Sack(int a, int b, int c, int d, int e)
{
sArray=new int[5];
sArray[0]=a;
sArray[1]=b;
sArray[2]=c;
sArray[3]=d;
sArray[4]=e;
}
/**********************************************************
Name: knapSack
Parameters: int targetWeight, int indx
Declared variables: int total
Return value: void
Algorithm:
**********************************************************/
public void knapSack(int indx, int target)// 11, 8, 7, 6, 5
{
int total=0, ans=0, tempIndx=indx;
int[] answers= new int[5];
if(sArray[tempIndx]==target)
{
System.out.println("The answer was found: "+sArray[indx]);
}
else if(sArray[tempIndx]>target)
{
++tempIndx;
}
ans+=sArray[tempIndx];//Adding up the answer.
answers[tempIndx]=sArray[tempIndx];//Putting the answers into the array.
total=target-sArray[tempIndx];
++tempIndx;
while(ans!=target && tempIndx<=5)
{
if(total>sArray[tempIndx])
{
ans+=sArray[tempIndx];//Adding up the answer.
answers[tempIndx]=sArray[tempIndx];//Putting the answers into the array.
total=target-sArray[tempIndx];
++tempIndx;
}
else
{
++tempIndx;
}
}
if(ans==target)
{
System.out.println("The answers are: "+sArray.toString());
}
else
{
++indx;
knapSack(indx, target);
}
}
public static void main(String[] args)
{
Sack jake=new Sack(11,8,7,6,5);
jake.knapSack(0,20);
}
}
|
|