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

Side by Side Diff: chrome/browser/metrics/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: Add constructor for OddsAndValue 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/random_selector.h"
Alexei Svitkine (slow) 2015/09/11 21:00:54 I'm not convinced of this living in chrome/browser
dhsharp 2015/09/11 22:53:25 Works for me. Will work on that. (Not sure if you
6
7 #include <string>
8 #include <vector>
9
10 #include <base/logging.h>
Alexei Svitkine (slow) 2015/09/11 21:00:54 Nit: "'s for project includes.
dhsharp 2015/09/11 22:53:25 Oops. Done.
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 namespace metrics {
17
18 RandomSelector::RandomSelector() {}
19
20 RandomSelector::~RandomSelector() {}
21
22 double RandomSelector::SumOdds(const std::vector<OddsAndValue>& odds) {
23 double sum = 0.0;
24 for (const auto& odd : odds) {
25 sum += odd.weight;
26 }
27 return sum;
28 }
29
30 void RandomSelector::SetOdds(const std::vector<OddsAndValue>& odds) {
31 odds_ = odds;
32 sum_of_odds_ = SumOdds(odds_);
33 }
34
35 const std::vector<std::string>& RandomSelector::GetNext() {
36 // Get a random double between 0 and the sum.
37 double random = RandDoubleUpTo(sum_of_odds_);
38 // Figure out what it belongs to.
39 return GetKeyOf(random);
40 }
41
42 double RandomSelector::RandDoubleUpTo(double max) {
43 CHECK_GT(max, 0.0);
44 return max * base::RandDouble();
45 }
46
47 const std::vector<std::string>& RandomSelector::GetKeyOf(double value) {
48 double current = 0.0;
49 for (const auto& odd : odds_) {
50 current += odd.weight;
51 if (value < current) {
52 return odd.value;
53 }
54 }
55 NOTREACHED() << "Invalid value for key: " << value;
56 static const std::vector<std::string> kEmptyVector;
57 return kEmptyVector;
58 }
59
60 } // namespace metrics
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698