From fa108bd3fab5cc0cecdcccbac52138a9d6d4dacf Mon Sep 17 00:00:00 2001 From: vipviv <72593650+vipw007@users.noreply.github.com> Date: Fri, 25 Oct 2024 20:18:45 +0530 Subject: [PATCH] Create unbound knapsack --- unbound knapsack | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 unbound knapsack diff --git a/unbound knapsack b/unbound knapsack new file mode 100644 index 0000000..0d8f4fd --- /dev/null +++ b/unbound knapsack @@ -0,0 +1,40 @@ +// C++ implementation of the approach +#include +using namespace std; + +// Function to return the maximum required value +float knapSack(int W, float wt[], float val[], int n) +{ + + // maxratio will store the maximum value to weight + // ratio we can have for any item and maxindex + // will store the index of that element + float maxratio = INT_MIN; + int maxindex = 0; + + // Find the maximum ratio + for (int i = 0; i < n; i++) { + if ((val[i] / wt[i]) > maxratio) { + maxratio = (val[i] / wt[i]); + maxindex = i; + } + } + + // The item with the maximum value to + // weight ratio will be put into + // the knapsack repeatedly until full + return (W * maxratio); +} + +// Driver code +int main() +{ + float val[] = { 14, 27, 44, 19 }; + float wt[] = { 6, 7, 9, 8 }; + int n = sizeof(val) / sizeof(val[0]); + int W = 50; + + cout << knapSack(W, wt, val, n); + + return 0; +}