|
| 1 | +import java.util.Arrays; |
| 2 | +import java.util.Comparator; |
| 3 | + |
| 4 | +public class FractionalKnapSack |
| 5 | +{ |
| 6 | + // Time complexity O(n log n) |
| 7 | + public static void main(String[] args) |
| 8 | + { |
| 9 | + int[] wt = {10, 40, 20, 30}; |
| 10 | + int[] val = {60, 40, 100, 120}; |
| 11 | + int capacity = 50; |
| 12 | + |
| 13 | + double maxValue = getMaxValue(wt, val, capacity); |
| 14 | + System.out.println("Maximum value we can obtain = " + |
| 15 | + maxValue); |
| 16 | + |
| 17 | + } |
| 18 | + |
| 19 | + // function to get maximum value |
| 20 | + private static double getMaxValue(int[] wt, |
| 21 | + int[] val, int capacity) |
| 22 | + { |
| 23 | + ItemValue[] iVal = new ItemValue[wt.length]; |
| 24 | + |
| 25 | + for(int i = 0; i < wt.length; i++) |
| 26 | + { |
| 27 | + iVal[i] = new ItemValue(wt[i], val[i], i); |
| 28 | + } |
| 29 | + |
| 30 | + //sorting items by value; |
| 31 | + Arrays.sort(iVal, new Comparator<ItemValue>() |
| 32 | + { |
| 33 | + @Override |
| 34 | + public int compare(ItemValue o1, ItemValue o2) |
| 35 | + { |
| 36 | + return o2.cost.compareTo(o1.cost) ; |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + |
| 41 | + double totalValue = 0d; |
| 42 | + |
| 43 | + for(ItemValue i: iVal) |
| 44 | + { |
| 45 | + |
| 46 | + int curWt = (int) i.wt; |
| 47 | + int curVal = (int) i.val; |
| 48 | + |
| 49 | + if (capacity - curWt >= 0) |
| 50 | + { |
| 51 | + // this weight can be picked while |
| 52 | + capacity = capacity-curWt; |
| 53 | + totalValue += curVal; |
| 54 | + |
| 55 | + } |
| 56 | + else |
| 57 | + { |
| 58 | + // item cant be picked whole |
| 59 | + double fraction = ((double)capacity/(double)curWt); |
| 60 | + totalValue += (curVal*fraction); |
| 61 | + capacity = (int)(capacity - (curWt*fraction)); |
| 62 | + break; |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | + } |
| 67 | + |
| 68 | + return totalValue; |
| 69 | + } |
| 70 | + static class ItemValue |
| 71 | + { |
| 72 | + Double cost; |
| 73 | + double wt, val, ind; |
| 74 | + public ItemValue(int wt, int val, int ind) |
| 75 | + { |
| 76 | + this.wt = wt; |
| 77 | + this.val = val; |
| 78 | + this.ind = ind; |
| 79 | + cost = new Double(val/wt ); |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments