Skip to content

Commit c0c5ed0

Browse files
author
=
committed
Fraction knapsack code added
1 parent d68ff9d commit c0c5ed0

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

greedy/a.out

3.99 KB
Binary file not shown.

greedy/fractionalknapsack.c

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include<stdio.h>
2+
int main()
3+
{
4+
int n,i,bag,itemp,j;
5+
printf("Enter the number of items: ");
6+
scanf("%d",&n);
7+
int profit[n],weight[n],item[n];
8+
float ppw[n],ftemp,p=0;
9+
for(i=0;i<n;i++)
10+
{
11+
printf("\n\nDetails of item number: %d\n",i+1);
12+
printf("Item name: ");
13+
scanf("%d",&item[i]);
14+
printf("Profit: ");
15+
scanf("%d",&profit[i]);
16+
printf("Weight: ");
17+
scanf("%d",&weight[i]);
18+
ppw[i]=(float)(profit[i]/weight[i]);
19+
}
20+
printf("\n\n");
21+
printf("Enter the weight of the bag: ");
22+
scanf("%d",&bag);
23+
printf("Sorting the process by profit per weight\n");
24+
for(i=0;i<n;i++)
25+
{
26+
for(j=i;j<n;j++)
27+
{
28+
if(ppw[i]<ppw[j])
29+
{
30+
ftemp=ppw[i];
31+
ppw[i]=ppw[j];
32+
ppw[j]=ftemp;
33+
itemp=profit[i];
34+
profit[i]=profit[j];
35+
profit[j]=itemp;
36+
itemp=weight[i];
37+
weight[i]=weight[j];
38+
weight[j]=itemp;
39+
itemp=item[i];
40+
item[i]=item[j];
41+
item[j]=itemp;
42+
}
43+
}
44+
}
45+
printf("\n\n");
46+
printf("Item name Profit Weight Profit per weight\n");
47+
for(i=0;i<n;i++)
48+
{
49+
printf("%d %d %d %f\n",item[i],profit[i],weight[i],ppw[i]);
50+
}
51+
while(bag>0)
52+
{
53+
for(i=0;i<n;i++)
54+
{
55+
if(bag>weight[i])
56+
{
57+
bag=bag-weight[i];
58+
p=p+profit[i];
59+
}
60+
else
61+
{
62+
p=p+ppw[i]*bag;
63+
bag=0;
64+
}
65+
}
66+
}
67+
printf("Total Profit by Knapsack problem is: %f\n",p);
68+
return 0;
69+
}

0 commit comments

Comments
 (0)