Chromium Code Reviews| Index: chrome/browser/metrics/random_selector.cc |
| diff --git a/chrome/browser/metrics/random_selector.cc b/chrome/browser/metrics/random_selector.cc |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..35340175964c4ac011f33a9af097d12c7c1cd668 |
| --- /dev/null |
| +++ b/chrome/browser/metrics/random_selector.cc |
| @@ -0,0 +1,60 @@ |
| +// 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/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
|
| + |
| +#include <string> |
| +#include <vector> |
| + |
| +#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.
|
| +#include <base/rand_util.h> |
| +#include <base/strings/string_number_conversions.h> |
| +#include <base/strings/string_split.h> |
| +#include <base/strings/string_util.h> |
| + |
| +namespace metrics { |
| + |
| +RandomSelector::RandomSelector() {} |
| + |
| +RandomSelector::~RandomSelector() {} |
| + |
| +double RandomSelector::SumOdds(const std::vector<OddsAndValue>& odds) { |
| + double sum = 0.0; |
| + for (const auto& odd : odds) { |
| + sum += odd.weight; |
| + } |
| + return sum; |
| +} |
| + |
| +void RandomSelector::SetOdds(const std::vector<OddsAndValue>& odds) { |
| + odds_ = odds; |
| + sum_of_odds_ = SumOdds(odds_); |
| +} |
| + |
| +const std::vector<std::string>& RandomSelector::GetNext() { |
| + // Get a random double between 0 and the sum. |
| + double random = RandDoubleUpTo(sum_of_odds_); |
| + // Figure out what it belongs to. |
| + return GetKeyOf(random); |
| +} |
| + |
| +double RandomSelector::RandDoubleUpTo(double max) { |
| + CHECK_GT(max, 0.0); |
| + return max * base::RandDouble(); |
| +} |
| + |
| +const std::vector<std::string>& RandomSelector::GetKeyOf(double value) { |
| + double current = 0.0; |
| + for (const auto& odd : odds_) { |
| + current += odd.weight; |
| + if (value < current) { |
| + return odd.value; |
| + } |
| + } |
| + NOTREACHED() << "Invalid value for key: " << value; |
| + static const std::vector<std::string> kEmptyVector; |
| + return kEmptyVector; |
| +} |
| + |
| +} // namespace metrics |