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 <string> | |
8 #include <vector> | |
Alexei Svitkine (slow)
2015/09/15 15:31:18
Nit: These two are not needed, because the header
dhsharp
2015/09/15 18:21:32
Done.
| |
9 | |
10 #include "base/logging.h" | |
11 #include "base/rand_util.h" | |
12 #include "base/strings/string_number_conversions.h" | |
13 #include "base/strings/string_split.h" | |
14 #include "base/strings/string_util.h" | |
15 | |
16 RandomSelector::RandomSelector() {} | |
Alexei Svitkine (slow)
2015/09/15 15:31:18
Nit: Initialize sum_of_odds_ - or tools like cover
dhsharp
2015/09/15 18:21:32
Done.
| |
17 | |
18 RandomSelector::~RandomSelector() {} | |
19 | |
20 double RandomSelector::SumWeights(const std::vector<WeightAndValue>& odds) { | |
21 double sum = 0.0; | |
22 for (const auto& odd : odds) { | |
23 sum += odd.weight; | |
24 } | |
25 return sum; | |
26 } | |
27 | |
28 void RandomSelector::SetOdds(const std::vector<WeightAndValue>& odds) { | |
29 odds_ = odds; | |
30 sum_of_odds_ = SumWeights(odds_); | |
31 } | |
32 | |
33 const std::string& RandomSelector::Select() { | |
34 // Get a random double between 0 and the sum. | |
35 double random = RandDoubleUpTo(sum_of_odds_); | |
36 // Figure out what it belongs to. | |
37 return GetValueFor(random); | |
38 } | |
39 | |
40 double RandomSelector::RandDoubleUpTo(double max) { | |
41 CHECK_GT(max, 0.0); | |
42 return max * base::RandDouble(); | |
43 } | |
44 | |
45 const std::string& RandomSelector::GetValueFor(double random) { | |
46 double current = 0.0; | |
47 for (const auto& odd : odds_) { | |
48 current += odd.weight; | |
49 if (random < current) | |
50 return odd.value; | |
51 } | |
52 NOTREACHED() << "Invalid value for key: " << random; | |
53 return base::EmptyString(); | |
54 } | |
OLD | NEW |