Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / browser / metrics / perf / random_selector.cc
blobe32c8a048d6c6c42d2ccdd9b858bd56ec08b29ac
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.
5 #include "chrome/browser/metrics/perf/random_selector.h"
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"
13 RandomSelector::RandomSelector() : sum_of_weights_(0) {}
15 RandomSelector::~RandomSelector() {}
17 double RandomSelector::SumWeights(const std::vector<WeightAndValue>& odds) {
18 double sum = 0.0;
19 for (const auto& odd : odds) {
20 sum += odd.weight;
22 return sum;
25 void RandomSelector::SetOdds(const std::vector<WeightAndValue>& odds) {
26 odds_ = odds;
27 sum_of_weights_ = SumWeights(odds_);
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);
37 double RandomSelector::RandDoubleUpTo(double max) {
38 CHECK_GT(max, 0.0);
39 return max * base::RandDouble();
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;
49 NOTREACHED() << "Invalid value for key: " << random;
50 return base::EmptyString();