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
) {
19 for (const auto& odd
: odds
) {
25 void RandomSelector::SetOdds(const std::vector
<WeightAndValue
>& 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
) {
39 return max
* base::RandDouble();
42 const std::string
& RandomSelector::GetValueFor(double random
) {
44 for (const auto& odd
: odds_
) {
45 current
+= odd
.weight
;
49 NOTREACHED() << "Invalid value for key: " << random
;
50 return base::EmptyString();