diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-13 19:10:05 +0100 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-13 20:30:16 +0100 |
commit | 2cf6b010e0a2fb678846d7a2e9ab64d23c49bb7b (patch) | |
tree | 79e6a3900fb3a288962cabd572ed942fc77b74c5 /01-algorithmic_toolbox/02-greedy_algorithms/02-fractional_knapsack | |
parent | e72410168143db1b79ee30e47d68cca2d730f740 (diff) | |
download | coursera-2cf6b010e0a2fb678846d7a2e9ab64d23c49bb7b.zip coursera-2cf6b010e0a2fb678846d7a2e9ab64d23c49bb7b.tar.gz |
Algorithms : complete 01-algorithmic_toolbox 02-greedy_algorithms
Diffstat (limited to '01-algorithmic_toolbox/02-greedy_algorithms/02-fractional_knapsack')
-rw-r--r-- | 01-algorithmic_toolbox/02-greedy_algorithms/02-fractional_knapsack/fractional_knapsack.cpp | 24 |
1 files changed, 22 insertions, 2 deletions
diff --git a/01-algorithmic_toolbox/02-greedy_algorithms/02-fractional_knapsack/fractional_knapsack.cpp b/01-algorithmic_toolbox/02-greedy_algorithms/02-fractional_knapsack/fractional_knapsack.cpp index 02e3fd8..7ab9b3f 100644 --- a/01-algorithmic_toolbox/02-greedy_algorithms/02-fractional_knapsack/fractional_knapsack.cpp +++ b/01-algorithmic_toolbox/02-greedy_algorithms/02-fractional_knapsack/fractional_knapsack.cpp @@ -3,10 +3,30 @@ using std::vector; -double get_optimal_value(int capacity, vector<int> weights, vector<int> values) { +double get_optimal_value(int capacity, vector<int> weights, vector<int> values) +{ double value = 0.0; - // write your code here + while ((capacity > 0) && (weights.size() > 0)) { + int idx = 0; + double ratio = 0.0; + for (int i = 0; i < weights.size(); i++) { + double r = ((double) values.at(i)) / weights.at(i); + if (r > ratio) { + idx = i; + ratio = r; + + } + } + double a = capacity; + if (weights[idx] < capacity) + a = weights[idx]; + + value += (ratio * a); + capacity -= a; + weights.erase(weights.begin()+idx); + values.erase(values.begin()+idx); + } return value; } |