From ef05f77f58345f3e2578b11c243797b978560fbe Mon Sep 17 00:00:00 2001 From: ashishdukare Date: Fri, 11 Oct 2019 19:38:10 +0530 Subject: [PATCH] Add comments-ashishdukare --- .../fractional_knapsack/fractional_knapsack.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/algorithmic_toolbox/week_3/02_greedy_algorithms_starter_files/fractional_knapsack/fractional_knapsack.cpp b/algorithmic_toolbox/week_3/02_greedy_algorithms_starter_files/fractional_knapsack/fractional_knapsack.cpp index 91f8024..2dbe5b4 100644 --- a/algorithmic_toolbox/week_3/02_greedy_algorithms_starter_files/fractional_knapsack/fractional_knapsack.cpp +++ b/algorithmic_toolbox/week_3/02_greedy_algorithms_starter_files/fractional_knapsack/fractional_knapsack.cpp @@ -3,6 +3,7 @@ using std::vector; +// finding the maximum index i.e the index for which values/weights is maximum int get_max_index(vector weights, vector values) { int max_i = 0; double max = 0; @@ -10,20 +11,21 @@ int get_max_index(vector weights, vector values) { for (int i = 0; i < weights.size(); i++) { if (weights[i] != 0 && (double) values[i] / weights[i] > max) { max = (double) values[i] / weights[i]; - max_i = i; + max_i = i; //maximum index } } return max_i; } +// filling the knapsack staring from the maximum index double get_optimal_value(int capacity, vector weights, vector values) { double value = 0.0; for (int i = 0; i < weights.size(); i++) { - if (capacity == 0) return value; + if (capacity == 0) return value; // capacity of the knapsack int index = get_max_index(weights, values); - int a = std::min(capacity, weights[index]); - value += a * (double) values[index] / weights[index]; + int a = std::min(capacity, weights[index]); + value += a * (double) values[index] / weights[index]; // total value of item placed in knapsack weights[index] -= a; capacity -= a; } @@ -43,7 +45,7 @@ int main() { double optimal_value = get_optimal_value(capacity, weights, values); - std::cout.precision(10); + std::cout.precision(10); //print the answer upto five decimal for error corrections std::cout << optimal_value << std::endl; return 0; }