Skip to content

Commit 6bd6ffe

Browse files
authored
Merge pull request #582 from madihamallick/master
Added Knapsack Problem in C
2 parents dc6113d + f56ecf1 commit 6bd6ffe

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*Write program to find the maximum profit and the solution vector for Knapsack problem.
2+
Consider the following constraints for knapsack. N=3, M=20
3+
Profit : 25 24 15
4+
Weight : 18 15 10
5+
*/
6+
7+
#include<stdio.h>
8+
#include<conio.h>
9+
int main(){
10+
int p[100],w[100],n,m,i,j,b,s,c;
11+
float Iv[100],a,profit,mul[100];
12+
printf("Enter knapsack capacity: ");
13+
scanf("%d",&m);
14+
printf("\nEnter number of data items: ");
15+
scanf("%d",&n);
16+
//profit array
17+
printf("\nEnter the values of profit array\n");
18+
for(i=1;i<=n;i++){
19+
printf("Enter p[%d] data item: ",i);
20+
scanf("%d",&p[i]);
21+
}
22+
//weight array
23+
printf("\nEnter the values of weight array\n");
24+
for(i=1;i<=n;i++){
25+
printf("Enter w[%d] data item: ",i);
26+
scanf("%d",&w[i]);
27+
}
28+
//I (profit/weight) value array
29+
for(i=1;i<=n;i++){
30+
Iv[i]= ((float)p[i]/(float)w[i]);
31+
}
32+
//sorting Iv,weight, and profit array
33+
for (i = 1; i <= n; i++){
34+
for (j = 1; j <= n; j++){
35+
if (Iv[j] < Iv[i]){
36+
a = Iv[i];
37+
b = w[i];
38+
c = p[i];
39+
Iv[i] = Iv[j];
40+
w[i] = w[j];
41+
p[i] = p[j];
42+
Iv[j] = a;
43+
w[j] = b;
44+
p[j]= c;
45+
}
46+
}
47+
}
48+
for(i=1;i<=n;i++){
49+
if(m==0){
50+
mul[i] = 0;
51+
break;
52+
}
53+
else {
54+
s = m - w[i];
55+
if (s>0){
56+
m = m - w[i];
57+
mul[i] = 1;
58+
}
59+
else{
60+
mul[i] = ((float)m/w[i]);
61+
m = m - (w[i] * ((float)m/w[i]));
62+
}
63+
}
64+
}
65+
for(i=1;i<=n;i++){
66+
profit += (mul[i] * p[i]);
67+
}
68+
printf("\nHence the total profit will be : %.2f\n",profit);
69+
//printing array Iv again
70+
printf("\nThe solution vector will be \n");
71+
for(i=1;i<=n;i++){
72+
printf("%.2f ",Iv[i]);
73+
}
74+
return 0;
75+
}

0 commit comments

Comments
 (0)