Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(508)

Side by Side Diff: chrome/browser/metrics/perf/random_selector.cc

Issue 1334943003: metrics: Add RandomSelector, a class that randomly selects items with odds (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Respond to comments on PS6 Created 5 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(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() {}
14
15 RandomSelector::~RandomSelector() : sum_of_weights_(0) {}
Simon Que 2015/09/16 21:38:40 You have constructor and destructor switched aroun
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 }
OLDNEW
« no previous file with comments | « chrome/browser/metrics/perf/random_selector.h ('k') | chrome/browser/metrics/perf/random_selector_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698