Saturday, June 10, 2017

java implementation of 0-1 knapsack problem by dynamic programming approach

Source code:

package dynamic;

public class Knapsack {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Program is running");

//input to the function 
int W=5;//knapsack capacity
int n=4;
int [] v={3,4,5,6};
int [] w={2,3,4,5};
 
int [][] c=dynamicKnapsack(W,n,v,w);
for(int i=0;i<=n;i++){
for(int j=0;j<=W;j++){
System.out.print(c[i][j]+"  ");
}
System.out.println();
}
 
solution(c,w,W,n);

}

public static int[][] dynamicKnapsack(int W, int n,int [] v,int w[]){

int [][] c=new int [n+1][W+1];//solution matrix



for(int i=0;i<=n;i++)
c[i][0]=0;

for(int weight=1;weight<=W;weight++)
c[0][weight]=0;

for(int i=1;i<=n;i++){
for(int weight =1;weight<=W;weight++){


if(w[i-1]<=weight){
if(c[i-1][weight] <c[i-1][weight -w[i-1]]+v[i-1])
{
c[i][weight]=c[i-1][weight -w[i-1]]+v[i-1];
}
else 
c[i][weight]=c[i-1][weight];
}
else
c[i][weight]=c[i-1][weight];


}

}


return c;

}
public static void solution (int [][]c,int [] weight,int W,int n){
System.out.println("Maximum Profit ="+c[n][W]);
for(int i=n;i>0;){
for(int w=W;w>0;){
if(c[i][w]!=c[i-1][w]){
System.out.println("Add item "+ (i-1));
i--;
w=w-weight[i];

}
else i--;w--;
}
}


}



}

No comments:

Post a Comment

Socket Programming in Java

Source Code: client Side: package learning; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event....