Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / browser / metrics / perf / random_selector.h
blob4500525d50bd5a841560be384e55cc4fd152b18f
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.
5 #ifndef CHROME_BROWSER_METRICS_PERF_RANDOM_SELECTOR_H_
6 #define CHROME_BROWSER_METRICS_PERF_RANDOM_SELECTOR_H_
8 #include <string>
9 #include <vector>
11 #include "base/macros.h"
13 // RandomSelector can be used to pick vectors of strings according to certain
14 // probabilities. The probabilities are set using SetOdds(). A randomly picked
15 // vector can be obtained by calling Select().
17 // Sample usage:
19 // RandomSelector random_selector;
20 // std::vector<RandomSelector::WeightAndValue> odds {
21 // {50, "a"},
22 // {40, "b"},
23 // {10, "c"}
24 // };
25 // random_selector.SetOdds(odds);
27 // std::vector<std::string>& selection = random_selector.Select();
29 // The above line should return "a" with a probability of 50%,
30 // "b" with a probability of 40%, and "c" with a probability of 10%:
31 class RandomSelector {
32 public:
33 struct WeightAndValue {
34 WeightAndValue(double weight, const std::string& value)
35 : weight(weight), value(value) {
38 // Probability weight for selecting this value.
39 double weight;
40 // Value to be returned by Select(), if selected.
41 std::string value;
44 RandomSelector();
45 virtual ~RandomSelector();
47 // Set the probabilities for various strings.
48 void SetOdds(const std::vector<WeightAndValue>& odds);
50 // Randomly select one of the values from the set.
51 const std::string& Select();
53 // Returns the number of string entries.
54 size_t num_values() const {
55 return odds_.size();
58 // Sum of the |weight| fields in the vector.
59 static double SumWeights(const std::vector<WeightAndValue>& odds);
61 private:
62 // Get a floating point number between 0.0 and |max|.
63 virtual double RandDoubleUpTo(double max);
65 // Get a string corresponding to |random| that is in the odds vector.
66 // |random| must be a number between zero and the sum of the probability
67 // weights.
68 const std::string& GetValueFor(double random);
70 // A dictionary representing the strings to choose from and associated odds.
71 std::vector<WeightAndValue> odds_;
73 // Sum of the probability weights.
74 double sum_of_weights_;
76 DISALLOW_COPY_AND_ASSIGN(RandomSelector);
79 #endif // CHROME_BROWSER_METRICS_PERF_RANDOM_SELECTOR_H_