-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
frac_knapsack.java
76 lines (55 loc) · 1.62 KB
/
frac_knapsack.java
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
71
72
73
74
75
76
// Java program to solve fractional Knapsack Problem
import java.util.Arrays;
import java.util.Comparator;
//Greedy approach
public class FractionalKnapSack {
//Time complexity O(n log n)
public static void main(String[] args){
int[] wt = {10, 40, 20, 30};
int[] val = {60, 40, 100, 120};
int capacity = 50;
double maxValue = getMaxValue(wt, val, capacity);
System.out.println("Maximum value we can obtain = "+maxValue);
}
// // function to get maximum value
private static double getMaxValue(int[] wt, int[] val, int capacity){
ItemValue[] iVal = new ItemValue[wt.length];
for(int i = 0; i < wt.length; i++){
iVal[i] = new ItemValue(wt[i], val[i], i);
}
//sorting items by value;
Arrays.sort(iVal, new Comparator<ItemValue>() {
@Override
public int compare(ItemValue o1, ItemValue o2) {
return o2.cost.compareTo(o1.cost) ;
}
});
double totalValue = 0d;
for(ItemValue i: iVal){
int curWt = (int) i.wt;
int curVal = (int) i.val;
if (capacity - curWt >= 0){//this weight can be picked while
capacity = capacity-curWt;
totalValue += curVal;
}else{//item cant be picked whole
double fraction = ((double)capacity/(double)curWt);
totalValue += (curVal*fraction);
capacity = (int)(capacity - (curWt*fraction));
break;
}
}
return totalValue;
}
// item value class
static class ItemValue {
Double cost;
double wt, val, ind;
// item value function
public ItemValue(int wt, int val, int ind){
this.wt = wt;
this.val = val;
this.ind = ind;
cost = new Double(val/wt );
}
}
}