Skip to content

Commit e107583

Browse files
committed
Added Knapsack Problem in C
1 parent ce3dd92 commit e107583

File tree

1 file changed

+69
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)