The Artima Developer Community
Sponsored Link

Java Answers Forum
KnapSack problem

6 replies on 1 page. Most recent reply: May 22, 2008 9:31 AM by prashant jalasutram

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 6 replies on 1 page
jake

Posts: 83
Nickname: onorok
Registered: May, 2002

KnapSack problem Posted: May 15, 2003 8:29 PM
Reply to this message Reply
Advertisement
YOu have a target weight and a bag of weights, I need to find out what weights make up that target weight. I need to return these weights. This problem needs to be solved recursively.
can anyone help me out???


jake

Posts: 83
Nickname: onorok
Registered: May, 2002

Re: KnapSack problem Posted: May 16, 2003 3:17 AM
Reply to this message Reply
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);
	}
}

jake

Posts: 83
Nickname: onorok
Registered: May, 2002

Re: KnapSack problem Posted: May 16, 2003 11:05 AM
Reply to this message Reply
can someone help me out here???...anyone???

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: KnapSack problem Posted: May 17, 2003 6:15 AM
Reply to this message Reply
public class Weights{
 
    private Sack bagOfWeights = new Sack();
    private Sack knapSack = new Sack();
 
    public static void main(String[] args){
        Weights myWeights = new Weights();
        /* Fill the bag of weights. */
        myWeights.bagOfWeights.add(11);
        myWeights.bagOfWeights.add(8);
        myWeights.bagOfWeights.add(7);
        myWeights.bagOfWeights.add(6);
        myWeights.bagOfWeights.add(5);
        myWeights.fillKnapSack(20);
        System.out.println("Knap sack contains the following weights: ");
        for (int i = 0; i < myWeights.knapSack.getWeights().length; i++){
            System.out.println(myWeights.knapSack.getWeight(i));
        }
        System.out.println("Total weight: " + myWeights.knapSack.getWeight());
    }
    
    public void fillKnapSack(int maxWeight){
        boolean isFull = false;
        for (int i = 0; i < bagOfWeights.getWeights().length; i++){
            if (knapSack.getWeight() + bagOfWeights.getWeight(i) < maxWeight){
                knapSack.add(bagOfWeights.getWeight(i));
                bagOfWeights.remove(i);
                break;
            }
            /* No more weights can be added to knapsack from bagOfWeights. */
            if (i == bagOfWeights.getWeights().length -1) isFull = true;                
            /* No more weights from to add bagOfWeights. */
            if (bagOfWeights.isEmpty()) isFull = true;
        }
        if (!isFull) fillKnapSack(maxWeight);
    }
    
    class Sack{
        private int[] weights;
    
        public void add(int weight){
            if (weights == null){
                weights = new int[1];
                weights[0] = weight;
            }else{
                int[] newWeights = new int[weights.length + 1];
                for (int i = 0; i < weights.length; i++){
                    newWeights[i] = weights[i];
                }
                newWeights[newWeights.length - 1] = weight;
                weights = newWeights;
            }
        }
    
        public void remove(int n){
            if (weights == null) return;
            int[] newWeights = new int[weights.length - 1];
            for (int i = 0;i < weights.length;i++){
                if (i < n) newWeights[i] = weights[i];
                if (i > n) newWeights[i-1] = weights[i];
            }
            weights = newWeights;
        }
    
        public int getWeight(){
            int sackWeight = 0;
            if (weights != null){
                for (int i = 0; i < weights.length; i++){
                    sackWeight = sackWeight + weights[i];
                }
            }
            return sackWeight;    
        }
    
        public int getWeight(int n){
            int w = -1;
            if (n < weights.length){
                w = weights[n];
            }
            return w;
        }
        
        public int[] getWeights(){
            return weights;   
        }
        
        public boolean isEmpty(){
            return (getWeight() == 0);
        }
        
    }
}
[java]

jake

Posts: 83
Nickname: onorok
Registered: May, 2002

Re: KnapSack problem Posted: May 17, 2003 1:21 PM
Reply to this message Reply
The program has to not add up all the weights in the sack, but rather find the combination of weights in a sack that can equal the target weight.
ex.
sack of weights=[11,8,7,6,5] target weight=20
answer: 8,7,5

anyone know how to solve this recursively???

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: KnapSack problem Posted: May 17, 2003 2:14 PM
Reply to this message Reply
import java.util.*;
 
public class Weights{
 
    private Sack bagOfWeights = new Sack();
    private Sack knapSack = new Sack();
 
    public static void main(String[] args){
        Weights myWeights = new Weights();
        /* Fill the bag of weights. */
        myWeights.bagOfWeights.add(11);
        myWeights.bagOfWeights.add(8);
        myWeights.bagOfWeights.add(7);
        myWeights.bagOfWeights.add(6);
        myWeights.bagOfWeights.add(5);
        myWeights.fillKnapSack(20);
        System.out.println("Knap sack contains the following weights: ");
        for (int i = 0; i < myWeights.knapSack.size(); i++){
            System.out.println(myWeights.knapSack.getWeight(i));
        }
    }
    
    public void fillKnapSack(int targetWeight){
        knapSack.empty();
        bagOfWeights.shuffle();
        for (int i = 0; i < bagOfWeights.size(); i++){
            if (knapSack.getWeight() + bagOfWeights.getWeight(i) <= targetWeight){
                knapSack.add(bagOfWeights.getWeight(i));
            }
        }
        /* Check to see if target weight was found. */
        if (knapSack.getWeight() != targetWeight) fillKnapSack(targetWeight);
    }
    
    class Sack extends ArrayList{
        
        public Sack(){
            super();
        }
    
        public void add(int weight){
            add(new Integer(weight));
        }
    
    
        public int getWeight(){
            int sackWeight = 0;
            for (int i = 0; i < size(); i++){
                Integer nextWeight = (Integer)get(i);
                sackWeight = sackWeight + nextWeight.intValue();
            }
            return sackWeight;    
        }
    
        public int getWeight(int n){
            int w = -1;
            if (n < size()){
                Integer weight = (Integer)get(n);
                w = weight.intValue();
            }
            return w;
        }
                
        public boolean isEmpty(){
            return (size() == 0);
        }
        
        public void shuffle(){
            Collections.shuffle((List)this);
        }
        
        public void empty(){
            clear();
        }
        
    }
}

prashant jalasutram

Posts: 1
Nickname: jalasutp
Registered: May, 2008

Re: KnapSack problem Posted: May 22, 2008 9:31 AM
Reply to this message Reply
Hi,

Probably you may try this version.

package Chap06.knapsackProblem;

public class KnapSackDemo {

private static int[] knapSack(int[] originalArr,int target) {
int targetArr[]=new int[originalArr.length];
int targetCounter=0;
int sum=0;

outer:
for(int i=0;i<originalArr.length;i++) {
sum=0;targetCounter=0;
int elem=originalArr;
targetArr[targetCounter]=elem;
sum+=elem;

for(int k=i;k<originalArr.length;k++) {
sum=0;targetCounter=0; targetArr=new int[originalArr.length];
targetArr[targetCounter]=elem;
sum+=elem;

for(int j=k+1;j<originalArr.length;j++) {
sum=sum+ originalArr[j];

if(sum < target) {
targetCounter++;
targetArr[targetCounter]=originalArr[j];
}

if(sum > target) {
sum=sum-originalArr[j];
continue;
}

if(sum==target) {
targetCounter++;
targetArr[targetCounter]=originalArr[j];
break outer;
}
}
}
}
return targetArr;
}

public static void main(String[] args) {
int[] originalArr=new int[] { 11,8,7,6,5};
int[] target=knapSack(originalArr,23);
for (int i : target) {
System.out.println(i);
}
}
}

Thanks
Prashant
http://prashantjalasutram.blogspot.com/

Flat View: This topic has 6 replies on 1 page
Topic: Batch File: error SETting a variable within a FOR /F loop Previous Topic   Next Topic Topic: JSF Tutorial

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use