-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathksack.c
70 lines (58 loc) · 1.47 KB
/
ksack.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/******************************************
*
* Knapsack Problem (fractional)
*
* Harsimran Singh
*
*
******************************************/
#include<stdio.h>
int main()
{
int n, i, j;
float weight[100], price[100]; //supporting only 100 items
printf("enter the number of items: ");
scanf("%d", &n);
for (i = 0 ; i < n; i++)
{
scanf("%f %f", &weight[i], &price[i]);
}
float maxweight;
printf("Enter the maximum weight to carry: ");
scanf("%f", &maxweight);
//sorting the list by price to weight
for (i = 0; i < n; i++)
{
for (j = i+1 ; j < n; j++)
{
if(price[i]/weight[i] < price[j]/weight[j])
{
int temp_p = price[i];
int temp_w = weight[i];
price[i] = price[j];
weight[i] = weight[j];
price[j] = temp_p;
weight[j] = temp_w;
}
}
}
printf("sorted the list\n");
float weightPicked = 0, totalPrice = 0;
int currentItem = 0;
//pick up the items till bag not full
while(weight[currentItem] <= (maxweight - weightPicked) && currentItem < n)
{
weightPicked += weight[currentItem];
totalPrice += price[currentItem];
currentItem++;
}
//pick the remaining weight
if (weightPicked != maxweight && currentItem < n)
{
float percentPick = (maxweight - weightPicked)/ weight[currentItem];
totalPrice += price[currentItem] * percentPick;
}
printf("The total price is : %f\n", totalPrice);
return 0;
}