-
Notifications
You must be signed in to change notification settings - Fork 656
/
Copy pathfractionalKnapsackJava
37 lines (31 loc) · 992 Bytes
/
fractionalKnapsackJava
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
class itemComparator implements Comparator<Item>
{
@Override
public int compare(Item a, Item b)
{
double r1 = (double)(a.value) / (double)(a.weight);
double r2 = (double)(b.value) / (double)(b.weight);
if(r1 < r2) return 1;
else if(r1 > r2) return -1;
else return 0;
}
}
class solve{
double fractionalKnapsack(int W, Item arr[], int n) {
Arrays.sort(arr, new itemComparator());
int curWeight = 0;
double finalvalue = 0.0;
for (int i = 0; i < n; i++) {
if (curWeight + arr[i].weight <= W) {
curWeight += arr[i].weight;
finalvalue += arr[i].value;
}
else {
int remain = W - curWeight;
finalvalue += ((double)arr[i].value / (double)arr[i].weight) * (double)remain;
break;
}
}
return finalvalue;
}
}