forked from fnplus/interview-techdev-guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fractional_Knapsack_Problem.java: Implement Fractional Knapsack Probl…
…em in java
- Loading branch information
[Tushar Gupta]
committed
Oct 7, 2019
1 parent
f722f13
commit cfd97ef
Showing
1 changed file
with
82 additions
and
0 deletions.
There are no files selected for viewing
82 changes: 82 additions & 0 deletions
82
Algorithms/Dynamic Programming/Fractional_Knapsack_Problem.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
import java.util.Arrays; | ||
import java.util.Comparator; | ||
|
||
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; | ||
} | ||
static class ItemValue | ||
{ | ||
Double cost; | ||
double wt, val, ind; | ||
public ItemValue(int wt, int val, int ind) | ||
{ | ||
this.wt = wt; | ||
this.val = val; | ||
this.ind = ind; | ||
cost = new Double(val/wt ); | ||
} | ||
} | ||
} |