OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "chrome/browser/metrics/perf/random_selector.h" |
| 6 |
| 7 #include "base/logging.h" |
| 8 #include "base/rand_util.h" |
| 9 #include "base/strings/string_number_conversions.h" |
| 10 #include "base/strings/string_split.h" |
| 11 #include "base/strings/string_util.h" |
| 12 |
| 13 RandomSelector::RandomSelector() : sum_of_weights_(0) {} |
| 14 |
| 15 RandomSelector::~RandomSelector() {} |
| 16 |
| 17 double RandomSelector::SumWeights(const std::vector<WeightAndValue>& odds) { |
| 18 double sum = 0.0; |
| 19 for (const auto& odd : odds) { |
| 20 sum += odd.weight; |
| 21 } |
| 22 return sum; |
| 23 } |
| 24 |
| 25 void RandomSelector::SetOdds(const std::vector<WeightAndValue>& odds) { |
| 26 odds_ = odds; |
| 27 sum_of_weights_ = SumWeights(odds_); |
| 28 } |
| 29 |
| 30 const std::string& RandomSelector::Select() { |
| 31 // Get a random double between 0 and the sum. |
| 32 double random = RandDoubleUpTo(sum_of_weights_); |
| 33 // Figure out what it belongs to. |
| 34 return GetValueFor(random); |
| 35 } |
| 36 |
| 37 double RandomSelector::RandDoubleUpTo(double max) { |
| 38 CHECK_GT(max, 0.0); |
| 39 return max * base::RandDouble(); |
| 40 } |
| 41 |
| 42 const std::string& RandomSelector::GetValueFor(double random) { |
| 43 double current = 0.0; |
| 44 for (const auto& odd : odds_) { |
| 45 current += odd.weight; |
| 46 if (random < current) |
| 47 return odd.value; |
| 48 } |
| 49 NOTREACHED() << "Invalid value for key: " << random; |
| 50 return base::EmptyString(); |
| 51 } |
OLD | NEW |