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

Unified 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: Fix dumb error 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 side-by-side diff with in-line comments
Download patch
Index: chrome/browser/metrics/perf/random_selector.cc
diff --git a/chrome/browser/metrics/perf/random_selector.cc b/chrome/browser/metrics/perf/random_selector.cc
new file mode 100644
index 0000000000000000000000000000000000000000..e32c8a048d6c6c42d2ccdd9b858bd56ec08b29ac
--- /dev/null
+++ b/chrome/browser/metrics/perf/random_selector.cc
@@ -0,0 +1,51 @@
+// Copyright 2015 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/metrics/perf/random_selector.h"
+
+#include "base/logging.h"
+#include "base/rand_util.h"
+#include "base/strings/string_number_conversions.h"
+#include "base/strings/string_split.h"
+#include "base/strings/string_util.h"
+
+RandomSelector::RandomSelector() : sum_of_weights_(0) {}
+
+RandomSelector::~RandomSelector() {}
+
+double RandomSelector::SumWeights(const std::vector<WeightAndValue>& odds) {
+ double sum = 0.0;
+ for (const auto& odd : odds) {
+ sum += odd.weight;
+ }
+ return sum;
+}
+
+void RandomSelector::SetOdds(const std::vector<WeightAndValue>& odds) {
+ odds_ = odds;
+ sum_of_weights_ = SumWeights(odds_);
+}
+
+const std::string& RandomSelector::Select() {
+ // Get a random double between 0 and the sum.
+ double random = RandDoubleUpTo(sum_of_weights_);
+ // Figure out what it belongs to.
+ return GetValueFor(random);
+}
+
+double RandomSelector::RandDoubleUpTo(double max) {
+ CHECK_GT(max, 0.0);
+ return max * base::RandDouble();
+}
+
+const std::string& RandomSelector::GetValueFor(double random) {
+ double current = 0.0;
+ for (const auto& odd : odds_) {
+ current += odd.weight;
+ if (random < current)
+ return odd.value;
+ }
+ NOTREACHED() << "Invalid value for key: " << random;
+ return base::EmptyString();
+}
« 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