diff --git a/algorithms/Knapsack Problem/cpp/knapsack.cpp b/algorithms/Knapsack Problem/cpp/knapsack.cpp new file mode 100644 index 00000000..8399b9db --- /dev/null +++ b/algorithms/Knapsack Problem/cpp/knapsack.cpp @@ -0,0 +1,62 @@ +#include +using namespace std; + +struct Item { + int value, weight; + + + Item(int value, int weight) + { + this->value=value; + this->weight=weight; + } +}; + + +bool cmp(struct Item a, struct Item b) +{ + double r1 = (double)a.value / (double)a.weight; + double r2 = (double)b.value / (double)b.weight; + return r1 > r2; +} + + +double fractionalKnapsack(int W, struct Item arr[], int n) +{ + sort(arr, arr + n, cmp); + + 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 += arr[i].value + * ((double)remain + / (double)arr[i].weight); + break; + } + } + + return finalvalue; +} + + +int main() +{ + int W = 50; + Item arr[] = { { 60, 10 }, { 100, 20 }, { 120, 30 } }; + + int n = sizeof(arr) / sizeof(arr[0]); + + + cout << fractionalKnapsack(W, arr, n); + return 0; +} \ No newline at end of file diff --git a/algorithms/Knapsack Problem/java/knapsack.java b/algorithms/Knapsack Problem/java/knapsack.java new file mode 100644 index 00000000..272fbcd8 --- /dev/null +++ b/algorithms/Knapsack Problem/java/knapsack.java @@ -0,0 +1,71 @@ +import java.util.*; + +public class FractionalKnapSack { + private static double getMax(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; + Arrays.sort(iVal, new Comparator() { + @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) { + capacity = capacity - curWt; + totalValue += curVal; + } + else { + double rem + = ((double)capacity / (double)curWt); + totalValue += (curVal * rem); + capacity + = (int)(capacity - (curWt * rem)); + 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((double)val / (double)wt); + } + } + + public static void main(String[] args) + { + int[] wt = { 10, 40, 20, 30 }; + int[] val = { 60, 40, 100, 120 }; + int capacity = 50; + + double maxValue = getMax(wt, val, capacity); + + + System.out.println(maxValue); + } +} \ No newline at end of file